<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>JavaKeeper</title>
    <meta name="generator" content="VuePress 1.5.4">
    <link rel="icon" href="/icon.svg">
    <script>
        var _hmt = _hmt || [];
        (function() {
            var hm = document.createElement("script");
            hm.src = "https://hm.baidu.com/hm.js?a949a9b30eb86ac0159e735ff8670c03";
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(hm, s);
            // 引入谷歌,不需要可删除这段
            var hm1 = document.createElement("script");
            hm1.src = "https://www.googletagmanager.com/gtag/js?id=UA-169923503-1";
            var s1 = document.getElementsByTagName("script")[0]; 
            s1.parentNode.insertBefore(hm1, s1);
        })();
        // 谷歌加载,不需要可删除
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'UA-169923503-1');
    </script>
    <meta name="description" content="">
    <meta name="keywords" content="JavaKeeper,Java,Java开发,算法,blog">
    <link rel="preload" href="/assets/css/0.styles.91f57736.css" as="style"><link rel="preload" href="/assets/js/app.447d4224.js" as="script"><link rel="preload" href="/assets/js/3.9d76740c.js" as="script"><link rel="preload" href="/assets/js/1.c4fd7d2e.js" as="script"><link rel="preload" href="/assets/js/35.de8253eb.js" as="script"><link rel="prefetch" href="/assets/js/10.8cf3be2c.js"><link rel="prefetch" href="/assets/js/100.74f35ab8.js"><link rel="prefetch" href="/assets/js/101.7a062346.js"><link rel="prefetch" href="/assets/js/102.c9485235.js"><link rel="prefetch" href="/assets/js/103.d88a3805.js"><link rel="prefetch" href="/assets/js/104.6e034144.js"><link rel="prefetch" href="/assets/js/105.d22f7450.js"><link rel="prefetch" href="/assets/js/106.a6cb54b0.js"><link rel="prefetch" href="/assets/js/107.7b65e72b.js"><link rel="prefetch" href="/assets/js/108.eb5804bb.js"><link rel="prefetch" href="/assets/js/109.05f775e5.js"><link rel="prefetch" href="/assets/js/11.c54ae13c.js"><link rel="prefetch" href="/assets/js/110.51d3d641.js"><link rel="prefetch" href="/assets/js/111.022b64a7.js"><link rel="prefetch" href="/assets/js/112.da8afd52.js"><link rel="prefetch" href="/assets/js/113.05a17b18.js"><link rel="prefetch" href="/assets/js/114.8960d913.js"><link rel="prefetch" href="/assets/js/115.67919f68.js"><link rel="prefetch" href="/assets/js/116.62b0cd71.js"><link rel="prefetch" href="/assets/js/117.ebac3eff.js"><link rel="prefetch" href="/assets/js/118.ecd629bd.js"><link rel="prefetch" href="/assets/js/119.a09a0897.js"><link rel="prefetch" href="/assets/js/12.60aa3b24.js"><link rel="prefetch" href="/assets/js/120.bf639d3d.js"><link rel="prefetch" href="/assets/js/121.b89d0c8e.js"><link rel="prefetch" href="/assets/js/122.1a75ff83.js"><link rel="prefetch" href="/assets/js/123.d2127132.js"><link rel="prefetch" href="/assets/js/124.2caff9e0.js"><link rel="prefetch" href="/assets/js/125.9b9f966a.js"><link rel="prefetch" href="/assets/js/126.58cdfb3d.js"><link rel="prefetch" href="/assets/js/127.8ef09c53.js"><link rel="prefetch" href="/assets/js/128.efdc2ae4.js"><link rel="prefetch" href="/assets/js/129.e35cbc57.js"><link rel="prefetch" href="/assets/js/13.125c13a0.js"><link rel="prefetch" href="/assets/js/130.f01a55e3.js"><link rel="prefetch" href="/assets/js/131.65205f4a.js"><link rel="prefetch" href="/assets/js/132.f42c5a0a.js"><link rel="prefetch" href="/assets/js/133.9ba468b3.js"><link rel="prefetch" href="/assets/js/134.7b597ba9.js"><link rel="prefetch" href="/assets/js/135.fb828b9a.js"><link rel="prefetch" href="/assets/js/136.3887532f.js"><link rel="prefetch" href="/assets/js/137.549bae01.js"><link rel="prefetch" href="/assets/js/138.db8d423d.js"><link rel="prefetch" href="/assets/js/139.dbaf2267.js"><link rel="prefetch" href="/assets/js/14.bd1d0b0d.js"><link rel="prefetch" href="/assets/js/140.6cb65fdc.js"><link rel="prefetch" href="/assets/js/141.9bd6cc4b.js"><link rel="prefetch" href="/assets/js/142.552db5ed.js"><link rel="prefetch" href="/assets/js/143.2c9f2bf4.js"><link rel="prefetch" href="/assets/js/144.fba98a15.js"><link rel="prefetch" href="/assets/js/145.c42f3a21.js"><link rel="prefetch" href="/assets/js/146.596d4d33.js"><link rel="prefetch" href="/assets/js/147.c48ae5c1.js"><link rel="prefetch" href="/assets/js/148.71064871.js"><link rel="prefetch" href="/assets/js/149.16582d21.js"><link rel="prefetch" href="/assets/js/15.f247873b.js"><link rel="prefetch" href="/assets/js/150.ead09aca.js"><link rel="prefetch" href="/assets/js/151.971fdf4b.js"><link rel="prefetch" href="/assets/js/152.369c9362.js"><link rel="prefetch" href="/assets/js/153.371edd15.js"><link rel="prefetch" href="/assets/js/154.e090b491.js"><link rel="prefetch" href="/assets/js/155.c68bf602.js"><link rel="prefetch" href="/assets/js/156.304aea8d.js"><link rel="prefetch" href="/assets/js/157.83beef7f.js"><link rel="prefetch" href="/assets/js/158.bb1794b0.js"><link rel="prefetch" href="/assets/js/159.2d54e792.js"><link rel="prefetch" href="/assets/js/16.04336c71.js"><link rel="prefetch" href="/assets/js/160.99d56586.js"><link rel="prefetch" href="/assets/js/161.edf660aa.js"><link rel="prefetch" href="/assets/js/162.0b84606e.js"><link rel="prefetch" href="/assets/js/163.b59e0d60.js"><link rel="prefetch" href="/assets/js/164.d9eb8228.js"><link rel="prefetch" href="/assets/js/165.ca624c79.js"><link rel="prefetch" href="/assets/js/166.025b2ba1.js"><link rel="prefetch" href="/assets/js/167.abc982cc.js"><link rel="prefetch" href="/assets/js/168.27ca13dc.js"><link rel="prefetch" href="/assets/js/169.41e753a2.js"><link rel="prefetch" href="/assets/js/17.43b3c1c8.js"><link rel="prefetch" href="/assets/js/170.626319e1.js"><link rel="prefetch" href="/assets/js/171.a221dddf.js"><link rel="prefetch" href="/assets/js/172.464b2361.js"><link rel="prefetch" href="/assets/js/173.96a3afee.js"><link rel="prefetch" href="/assets/js/174.116607c2.js"><link rel="prefetch" href="/assets/js/175.ea3e8659.js"><link rel="prefetch" href="/assets/js/176.7d7b8afc.js"><link rel="prefetch" href="/assets/js/177.a6e00aa0.js"><link rel="prefetch" href="/assets/js/178.1f93afaf.js"><link rel="prefetch" href="/assets/js/179.3aa00dcd.js"><link rel="prefetch" href="/assets/js/18.d81b44d5.js"><link rel="prefetch" href="/assets/js/180.f8b2b75a.js"><link rel="prefetch" href="/assets/js/181.8e11258a.js"><link rel="prefetch" href="/assets/js/182.22243941.js"><link rel="prefetch" href="/assets/js/183.d051fdf6.js"><link rel="prefetch" href="/assets/js/184.a994075e.js"><link rel="prefetch" href="/assets/js/185.776c7e16.js"><link rel="prefetch" href="/assets/js/186.f1887955.js"><link rel="prefetch" href="/assets/js/187.da0d3626.js"><link rel="prefetch" href="/assets/js/188.8dfc358f.js"><link rel="prefetch" href="/assets/js/189.dcac5a59.js"><link rel="prefetch" href="/assets/js/19.1b3d66e1.js"><link rel="prefetch" href="/assets/js/190.c7e413d0.js"><link rel="prefetch" href="/assets/js/191.d9806121.js"><link rel="prefetch" href="/assets/js/192.869791da.js"><link rel="prefetch" href="/assets/js/193.2d74c4c8.js"><link rel="prefetch" href="/assets/js/194.c73a1909.js"><link rel="prefetch" href="/assets/js/195.e8c74834.js"><link rel="prefetch" href="/assets/js/20.bd5949ec.js"><link rel="prefetch" href="/assets/js/21.3fcf98cf.js"><link rel="prefetch" href="/assets/js/22.2fa1e2e8.js"><link rel="prefetch" href="/assets/js/23.1ae64bb4.js"><link rel="prefetch" href="/assets/js/24.7bdf7387.js"><link rel="prefetch" href="/assets/js/25.392c436e.js"><link rel="prefetch" href="/assets/js/26.58acbd4b.js"><link rel="prefetch" href="/assets/js/27.c725bdd5.js"><link rel="prefetch" href="/assets/js/28.6c9bda1e.js"><link rel="prefetch" href="/assets/js/29.e656b537.js"><link rel="prefetch" href="/assets/js/30.2c326fc7.js"><link rel="prefetch" href="/assets/js/31.e6c9fa30.js"><link rel="prefetch" href="/assets/js/32.c9c88437.js"><link rel="prefetch" href="/assets/js/33.0c53373c.js"><link rel="prefetch" href="/assets/js/34.9821e543.js"><link rel="prefetch" href="/assets/js/36.d182f929.js"><link rel="prefetch" href="/assets/js/37.9fa79014.js"><link rel="prefetch" href="/assets/js/38.9bebff76.js"><link rel="prefetch" href="/assets/js/39.19a3a2d4.js"><link rel="prefetch" href="/assets/js/4.564edb9d.js"><link rel="prefetch" href="/assets/js/40.cca6955f.js"><link rel="prefetch" href="/assets/js/41.854cd09a.js"><link rel="prefetch" href="/assets/js/42.ca7b612f.js"><link rel="prefetch" href="/assets/js/43.87027d58.js"><link rel="prefetch" href="/assets/js/44.8c2b4f4b.js"><link rel="prefetch" href="/assets/js/45.dffb4e08.js"><link rel="prefetch" href="/assets/js/46.f58049a5.js"><link rel="prefetch" href="/assets/js/47.6854070c.js"><link rel="prefetch" href="/assets/js/48.6cd9fa3d.js"><link rel="prefetch" href="/assets/js/49.e8861afa.js"><link rel="prefetch" href="/assets/js/5.5c31d62f.js"><link rel="prefetch" href="/assets/js/50.703bffab.js"><link rel="prefetch" href="/assets/js/51.6655c373.js"><link rel="prefetch" href="/assets/js/52.deb2eb09.js"><link rel="prefetch" href="/assets/js/53.6e0ed77d.js"><link rel="prefetch" href="/assets/js/54.b05c58ad.js"><link rel="prefetch" href="/assets/js/55.49c8164e.js"><link rel="prefetch" href="/assets/js/56.a5574e6b.js"><link rel="prefetch" href="/assets/js/57.58cb0de4.js"><link rel="prefetch" href="/assets/js/58.52345112.js"><link rel="prefetch" href="/assets/js/59.663ce78d.js"><link rel="prefetch" href="/assets/js/6.a9df34ee.js"><link rel="prefetch" href="/assets/js/60.f06adde2.js"><link rel="prefetch" href="/assets/js/61.170255a1.js"><link rel="prefetch" href="/assets/js/62.9d120050.js"><link rel="prefetch" href="/assets/js/63.70cced6b.js"><link rel="prefetch" href="/assets/js/64.577f3548.js"><link rel="prefetch" href="/assets/js/65.c037b29d.js"><link rel="prefetch" href="/assets/js/66.7dd1045f.js"><link rel="prefetch" href="/assets/js/67.d3aa4d6c.js"><link rel="prefetch" href="/assets/js/68.526dbb61.js"><link rel="prefetch" href="/assets/js/69.58269266.js"><link rel="prefetch" href="/assets/js/7.6609d4d6.js"><link rel="prefetch" href="/assets/js/70.64108f1b.js"><link rel="prefetch" href="/assets/js/71.1e95e0a6.js"><link rel="prefetch" href="/assets/js/72.42e7ec94.js"><link rel="prefetch" href="/assets/js/73.dad4e1c5.js"><link rel="prefetch" href="/assets/js/74.28ea286a.js"><link rel="prefetch" href="/assets/js/75.dd6d4c6f.js"><link rel="prefetch" href="/assets/js/76.ca6539df.js"><link rel="prefetch" href="/assets/js/77.feb13b0e.js"><link rel="prefetch" href="/assets/js/78.321e90e6.js"><link rel="prefetch" href="/assets/js/79.68eb8fcf.js"><link rel="prefetch" href="/assets/js/8.396d51fd.js"><link rel="prefetch" href="/assets/js/80.4edb5321.js"><link rel="prefetch" href="/assets/js/81.735d7e57.js"><link rel="prefetch" href="/assets/js/82.fa120bdf.js"><link rel="prefetch" href="/assets/js/83.bf755f94.js"><link rel="prefetch" href="/assets/js/84.9b32070c.js"><link rel="prefetch" href="/assets/js/85.592aca7c.js"><link rel="prefetch" href="/assets/js/86.4dcd9e73.js"><link rel="prefetch" href="/assets/js/87.a9e546aa.js"><link rel="prefetch" href="/assets/js/88.2a423212.js"><link rel="prefetch" href="/assets/js/89.5f455115.js"><link rel="prefetch" href="/assets/js/9.adb074c6.js"><link rel="prefetch" href="/assets/js/90.5202da0a.js"><link rel="prefetch" href="/assets/js/91.02cee99d.js"><link rel="prefetch" href="/assets/js/92.f16bad0b.js"><link rel="prefetch" href="/assets/js/93.f933634f.js"><link rel="prefetch" href="/assets/js/94.8e7b1d65.js"><link rel="prefetch" href="/assets/js/95.ee0e4a0a.js"><link rel="prefetch" href="/assets/js/96.e21d78c2.js"><link rel="prefetch" href="/assets/js/97.c87e514e.js"><link rel="prefetch" href="/assets/js/98.d123ac92.js"><link rel="prefetch" href="/assets/js/99.92d1b416.js">
    <link rel="stylesheet" href="/assets/css/0.styles.91f57736.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container no-sidebar" data-v-3ba18f14><div data-v-3ba18f14><div id="loader-wrapper" class="loading-wrapper" data-v-041fef5b data-v-3ba18f14 data-v-3ba18f14><div class="loader-main" data-v-041fef5b><div data-v-041fef5b></div><div data-v-041fef5b></div><div data-v-041fef5b></div><div data-v-041fef5b></div></div> <!----> <!----></div> <div class="password-shadow password-wrapper-out" style="display:none;" data-v-68139a52 data-v-3ba18f14 data-v-3ba18f14><h3 class="title" style="display:none;" data-v-68139a52 data-v-68139a52>JavaKeeper</h3> <!----> <label id="box" class="inputBox" style="display:none;" data-v-68139a52 data-v-68139a52><input type="password" value="" data-v-68139a52> <span data-v-68139a52>Konck! Knock!</span> <button data-v-68139a52>OK</button></label> <div class="footer" style="display:none;" data-v-68139a52 data-v-68139a52><span data-v-68139a52><i class="iconfont reco-theme" data-v-68139a52></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-68139a52>vuePress-theme-reco</a></span> <span data-v-68139a52><i class="iconfont reco-copyright" data-v-68139a52></i> <a data-v-68139a52><span data-v-68139a52>海星</span>
            
          <!---->
          2020
        </a></span></div></div> <div class="hide" data-v-3ba18f14><header class="navbar" data-v-3ba18f14><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><!----> <span class="site-name">JavaKeeper</span></a> <div class="links"><div class="color-picker"><a class="color-button"><i class="iconfont reco-color"></i></a> <div class="color-picker-menu" style="display:none;"><div class="mode-options"><h4 class="title">Choose mode</h4> <ul class="color-mode-options"><li class="dark">dark</li><li class="auto active">auto</li><li class="light">light</li></ul></div></div></div> <div class="search-box"><i class="iconfont reco-search"></i> <input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/java/" class="nav-link"><i class="iconfont undefined"></i>
  Java
</a></div><div class="nav-item"><a href="/data-structure-algorithms/" class="nav-link"><i class="iconfont undefined"></i>
  数据结构与算法
</a></div><div class="nav-item"><a href="/data-store/" class="nav-link"><i class="iconfont undefined"></i>
  数据存储与缓存
</a></div><div class="nav-item"><a href="/interview/" class="nav-link"><i class="iconfont undefined"></i>
  直击面试
</a></div> <a href="https://github.com/Jstarfish/JavaKeeper" target="_blank" rel="noopener noreferrer" class="repo-link"><i class="iconfont reco-github"></i>
    GitHub
    <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></nav></div></header> <div class="sidebar-mask" data-v-3ba18f14></div> <aside class="sidebar" data-v-3ba18f14><div class="personal-info-wrapper" data-v-5f6acefd data-v-3ba18f14><!----> <h3 class="name" data-v-5f6acefd>
    海星
  </h3> <div class="num" data-v-5f6acefd><div data-v-5f6acefd><h3 data-v-5f6acefd>0</h3> <h6 data-v-5f6acefd>Article</h6></div> <div data-v-5f6acefd><h3 data-v-5f6acefd>0</h3> <h6 data-v-5f6acefd>Tag</h6></div></div> <hr data-v-5f6acefd></div> <nav class="nav-links"><div class="nav-item"><a href="/java/" class="nav-link"><i class="iconfont undefined"></i>
  Java
</a></div><div class="nav-item"><a href="/data-structure-algorithms/" class="nav-link"><i class="iconfont undefined"></i>
  数据结构与算法
</a></div><div class="nav-item"><a href="/data-store/" class="nav-link"><i class="iconfont undefined"></i>
  数据存储与缓存
</a></div><div class="nav-item"><a href="/interview/" class="nav-link"><i class="iconfont undefined"></i>
  直击面试
</a></div> <a href="https://github.com/Jstarfish/JavaKeeper" target="_blank" rel="noopener noreferrer" class="repo-link"><i class="iconfont reco-github"></i>
    GitHub
    <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></nav> <!----> </aside> <div class="password-shadow password-wrapper-in" style="display:none;" data-v-68139a52 data-v-3ba18f14><h3 class="title" style="display:none;" data-v-68139a52 data-v-68139a52></h3> <!----> <label id="box" class="inputBox" style="display:none;" data-v-68139a52 data-v-68139a52><input type="password" value="" data-v-68139a52> <span data-v-68139a52>Konck! Knock!</span> <button data-v-68139a52>OK</button></label> <div class="footer" style="display:none;" data-v-68139a52 data-v-68139a52><span data-v-68139a52><i class="iconfont reco-theme" data-v-68139a52></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-68139a52>vuePress-theme-reco</a></span> <span data-v-68139a52><i class="iconfont reco-copyright" data-v-68139a52></i> <a data-v-68139a52><span data-v-68139a52>海星</span>
            
          <!---->
          2020
        </a></span></div></div> <div data-v-3ba18f14><main class="page"><div class="page-title" style="display:none;"><h1 class="title"></h1> <div data-v-5d8dbdb4><i class="iconfont reco-account" data-v-5d8dbdb4><span data-v-5d8dbdb4>海星</span></i> <!----> <!----> <!----></div></div> <div class="theme-reco-content content__default" style="display:none;"><blockquote><p>官方文档才是最好的入门学习文档：https://hadoop.apache.org/docs/r1.0.4/cn/mapred_tutorial.html</p></blockquote> <h2 id="一、mapreduce-概述"><a href="#一、mapreduce-概述" class="header-anchor">#</a> 一、MapReduce 概述</h2> <h3 id="_1-1-mapreduce-定义"><a href="#_1-1-mapreduce-定义" class="header-anchor">#</a> 1.1 MapReduce 定义</h3> <p>MapReduce 是一个<mark><strong>分布式运算程序的编程框架</strong></mark>，是用户开发“基于Hadoop的数据分析应用”的核心框架。基于它写出来的应用程序能够运行在由上千个商用机器组成的大型集群上，并以一种可靠容错的方式并行处理上T级别的数据集。</p> <p>MapReduce 核心功能是将<strong>用户编写的业务逻辑代码</strong>和<strong>自带默认组件</strong>整合成一个完整的<strong>分布式运算程序</strong>，并发运行在一个 Hadoop 集群上。</p> <p>一个Map/Reduce <em>作业（job）</em> 通常会把输入的数据集切分为若干独立的数据块，由 <em>map任务（task）<em>以完全并行的方式处理它们。框架会对map的输出先进行排序， 然后把结果输入给</em>reduce任务</em>。通常作业的输入和输出都会被存储在文件系统中。 整个框架负责任务的调度和监控，以及重新执行已经失败的任务。</p> <p>通常，Map/Reduce框架和<a href="https://hadoop.apache.org/docs/r1.0.4/cn/hdfs_design.html" target="_blank" rel="noopener noreferrer">分布式文件系统<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>是运行在一组相同的节点上的，也就是说，计算节点和存储节点通常在一起。这种配置允许框架在那些已经存好数据的节点上高效地调度任务，这可以使整个集群的网络带宽被非常高效地利用。</p> <p>Map/Reduce框架由一个单独的 master JobTracker 和每个集群节点一个 slave TaskTracker 共同组成。master 负责调度构成一个作业的所有任务，这些任务分布在不同的 slave 上，master 监控它们的执行，重新执行已经失败的任务。而 slave 仅负责执行由 master 指派的任务。</p> <p>应用程序至少应该指明输入/输出的位置（路径），并通过实现合适的接口或抽象类提供map和reduce函数。再加上其他作业的参数，就构成了<em>作业配置（job configuration）</em>。然后，Hadoop 的 <em>job client</em>提交作业（jar包/可执行程序等）和配置信息给 JobTracker，后者负责分发这些软件和配置信息给 slave、调度任务并监控它们的执行，同时提供状态和诊断信息给 job-client。</p> <p>虽然Hadoop框架是用JavaTM实现的，但Map/Reduce应用程序则不一定要用 Java来写 。</p> <ul><li><a href="https://hadoop.apache.org/core/docs/r0.18.2/api/org/apache/hadoop/streaming/package-summary.html" target="_blank" rel="noopener noreferrer">Hadoop Streaming<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>是一种运行作业的实用工具，它允许用户创建和运行任何可执行程序 （例如：Shell工具）来做为mapper和reducer。</li> <li><a href="https://hadoop.apache.org/core/docs/r0.18.2/api/org/apache/hadoop/mapred/pipes/package-summary.html" target="_blank" rel="noopener noreferrer">Hadoop Pipes<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>是一个与<a href="http://www.swig.org/" target="_blank" rel="noopener noreferrer">SWIG<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>兼容的C++ API （没有基于JNITM技术），它也可用于实现Map/Reduce应用程序。</li></ul> <h3 id="_1-2-mapreduce-优缺点"><a href="#_1-2-mapreduce-优缺点" class="header-anchor">#</a> 1.2 MapReduce 优缺点</h3> <h4 id="优点"><a href="#优点" class="header-anchor">#</a> 优点</h4> <ol><li><p><strong>易于编程</strong></p> <p>它简单的实现一些接口，就可以完成一个分布式程序，这个分布式程序可以分布到大量廉价的 PC机器上运行。也就是说你写一个分布式程序，跟写一个简单的串行程序是一模一样的。就是因为这个特点使得MapReduce 编程变得非常流行。</p></li> <li><p><strong>良好的扩展性</strong></p> <p>当你的计算资源不能得到满足的时候，你可以通过简单的增加机器来扩展它的计算能力。 MapReduce</p></li> <li><p><strong>高容错性</strong></p> <p>MapReduce 设计的初衷就是使程序能够部署在廉价的 PC 机器上，这就要求它具有很高的容错性。比如其中一台机器挂了，它可以把上面的计算任务 转移到另外一个节点上运行，不至于这个任务运行失败，而且这个过程不需要人工参与，而完全是由 Hadoop 内部完成的。</p></li> <li><p><strong>适合 PB 级以上海量数据的离线处理</strong></p> <p>可以实现上千台服务器集群并发工作，提供数据处理能力。</p></li></ol> <h4 id="缺点"><a href="#缺点" class="header-anchor">#</a> 缺点</h4> <ol><li><p><strong>不擅长实时计算</strong></p> <p>MapReduce 无法像 MySQL 一样，在毫秒或者秒级内返回结果。</p></li> <li><p><strong>不擅长流式计算</strong></p> <p>流式计算的输入数据是动态的，而 MapReduce 的输入数据集是静态的，不能动态变化。这是因为MapReduce 自身的设计特点决定了数据源必须是静态的。</p></li> <li><p><strong>不擅长DAG（有向图）计算</strong></p> <p>多个应用程序存在依赖关系，后一个应用程序的输入为前一个的输出。在这种情况下，MapReduce 并不是不能做，而是使用后，每个 MapReduce作业的输出结果都会写入到磁盘，会造成大量的磁盘 IO，导致性能非常的低下。</p></li></ol> <h3 id="_1-3-mapreduce-核心思想"><a href="#_1-3-mapreduce-核心思想" class="header-anchor">#</a> 1.3 MapReduce 核心思想</h3> <p><img src="https://imgkr.cn-bj.ufileos.com/3d068497-63b8-4e14-8100-8e63f9d835a9.png" alt="image-20200723104319403"></p> <ol><li>分布式的运算程序往往需要分成至少 2 个阶段。</li> <li>第一个阶段的 MapTask 并发实例，完全并行运行，互不相干。</li> <li>第二个阶段的 ReduceTask 并发实例互不相干，但是他们的数据依赖于上一个阶段的所有 MapTask 并发实例的输出。</li> <li>MapReduce 编程模型只能包含一个 Map 阶段和一个 Reduce 阶段，如果用户的业务逻辑非常复杂，那就只能多个 MapReduce 程序，串行运行。</li></ol> <h3 id="_1-4-mapreduce-进程"><a href="#_1-4-mapreduce-进程" class="header-anchor">#</a> 1.4 MapReduce 进程</h3> <p>一个完整的 MapReduce 程序在分布式运行时有三类实例进程：</p> <ol><li>MrAppMaster： 负责整个程序的过程调度及状态协调</li> <li>MapTask： 负责 Map 阶段的整个数据处理流程</li> <li>ReduceTask：负责 Reduce 阶段的整个数据处理流程</li></ol> <h3 id="_1-5-官方-wordcount-源码"><a href="#_1-5-官方-wordcount-源码" class="header-anchor">#</a> 1.5 官方 WordCount 源码</h3> <p>采用反编译工具反编译源码，发现 WordCount 案例有 Map 类、Reduce 类和驱动类。且数据的类型是 Hadoop 自身封装的序列化类型。</p> <h3 id="_1-6-常用数据序列化类型"><a href="#_1-6-常用数据序列化类型" class="header-anchor">#</a> 1.6 常用数据序列化类型</h3> <p><img src="https://imgkr.cn-bj.ufileos.com/9b598cd2-756c-48b7-8526-4d075dad916b.png" alt="image-20200723104612516"></p> <h3 id="_1-7-mapreduce-编程规范"><a href="#_1-7-mapreduce-编程规范" class="header-anchor">#</a> 1.7 MapReduce 编程规范</h3> <p>用户编写的程序分成三个部分：Mapper、Reducer 和 Driver。</p> <p>1、Mapper 阶段</p> <p>​	① 用户自定义的 Mapper 要继承自己的父类</p> <p>​	② Mapper 的输入数据是 KV 对的形式（KV的类型可自定义）</p> <p>​	③ Mapper 中的业务逻辑写在 map() 方法中</p> <p>​	④ Mapper 的输出数据是 KV 对的形式（KV 的类型可自定义）</p> <p>​	⑤ map() 方法（MapTask 进程）对每一个调用一次</p> <p>2、Reducer 阶段</p> <p>​	① 用户自定义的 Reducer 要继承自己的父类</p> <p>​	② Reducer 的输入数据类型对应 Mapper 的输出数据类型，也是KV</p> <p>​	③ Reducer 的业务逻辑写在 reduce() 方法中</p> <p>​	④ ReduceTask 进程对每一组相同k的组调用一次 reduce() 方法</p> <p>3、Driver 阶段</p> <p>​	相当于 YARN 集群的客户端，用于提交我们整个程序到 YARN 集群，提交的是封装了 MapReduce 程序相关运	行参数的 job 对象</p> <h3 id="_1-8-输入与输出"><a href="#_1-8-输入与输出" class="header-anchor">#</a> 1.8 输入与输出</h3> <p>Map/Reduce框架运转在&lt;key, value&gt; 键值对上，也就是说， 框架把作业的输入看为是一组&lt;key, value&gt; 键值对，同样也产出一组 &lt;key, value&gt; 键值对做为作业的输出，这两组键值对的类型可能不同。</p> <p>框架需要对key和value的类(classes)进行序列化操作， 因此，这些类需要实现 <a href="https://hadoop.apache.org/core/docs/r0.18.2/api/org/apache/hadoop/io/Writable.html" target="_blank" rel="noopener noreferrer">Writable<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>接口。 另外，为了方便框架执行排序操作，key类必须实现 <a href="https://hadoop.apache.org/core/docs/r0.18.2/api/org/apache/hadoop/io/WritableComparable.html" target="_blank" rel="noopener noreferrer">WritableComparable<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>接口。</p> <p>一个Map/Reduce 作业的输入和输出类型如下所示：</p> <p>(input) &lt;k1, v1&gt; -&gt; <strong>map</strong> -&gt; &lt;k2, v2&gt; -&gt; <strong>combine</strong> -&gt; &lt;k2, v2&gt; -&gt; <strong>reduce</strong> -&gt; &lt;k3, v3&gt; (output)</p> <h3 id="_1-9-hello-world"><a href="#_1-9-hello-world" class="header-anchor">#</a> 1.9 hello world</h3> <blockquote><p>我们用官方提供的 WordCount 例子</p></blockquote> <h2 id="二、hadoop-序列化"><a href="#二、hadoop-序列化" class="header-anchor">#</a> 二、Hadoop 序列化</h2> <h3 id="_2-1-序列化概述"><a href="#_2-1-序列化概述" class="header-anchor">#</a> 2.1 序列化概述</h3> <h4 id="_2-1-1-什么是序列化"><a href="#_2-1-1-什么是序列化" class="header-anchor">#</a> 2.1.1 什么是序列化</h4> <p>序列化就是把内存中的对象，转换成字节序列（或其他数据传输协议）以便于存储到磁盘（持久化）和网络传输。 反序列化就是将收到字节序列（或其他数据传输协议）或者是磁盘的持久化数据，转换成内存中的对象。</p> <h4 id="_2-1-2-为什么要序列化"><a href="#_2-1-2-为什么要序列化" class="header-anchor">#</a> 2.1.2 为什么要序列化</h4> <p>一般来说，“活的”对象只生存在内存里，关机断电就没有了。而且“活的” 对象只能由本地的进程使用，不能被发送到网络上的另外一台计算机。 然而序列化可以存储“活的”对象，可以将“活的”对象发送到远程计算机。</p> <h4 id="_2-1-3-为什么不用java的序列化"><a href="#_2-1-3-为什么不用java的序列化" class="header-anchor">#</a> 2.1.3 为什么不用Java的序列化</h4> <p>Java 的序列化是一个重量级序列化框架（Serializable），一个对象被序列化后，会附带很多额外的信息（各种校验信息，Header，继承体系等），不便于在网络中高效传输。所以，Hadoop 自己开发了一套序列化机制（Writable）。</p> <p><strong>Hadoop序列化特点：</strong></p> <ol><li>紧凑 ：高效使用存储空间</li> <li>快速：读写数据的额外开销小</li> <li>可扩展：随着通信协议的升级而可升级</li> <li>互操作：支持多语言的交互</li></ol> <h4 id="_2-2-自定义-bean-对象实现序列化接口-writable"><a href="#_2-2-自定义-bean-对象实现序列化接口-writable" class="header-anchor">#</a> 2.2 自定义 bean 对象实现序列化接口（Writable）</h4> <p>在企业开发中往往常用的基本序列化类型不能满足所有需求，比如在 Hadoop 框架内部传递一个 bean 对象，那么该对象就需要实现序列化接口。 具体实现 bean 对象序列化步骤如下 7 步。</p> <ol><li><p>必须实现 Writable 接口</p></li> <li><p>反序列化时，需要反射调用空参构造函数，所以必须有空参构造</p> <div class="language-java extra-class"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token class-name">FlowBean</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">super</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div></li> <li><p>重写序列化方法</p> <div class="language-java extra-class"><pre class="language-java"><code><span class="token annotation punctuation">@Override</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">write</span><span class="token punctuation">(</span><span class="token class-name">DataOutput</span> out<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">IOException</span> <span class="token punctuation">{</span>
	out<span class="token punctuation">.</span><span class="token function">writeLong</span><span class="token punctuation">(</span>upFlow<span class="token punctuation">)</span><span class="token punctuation">;</span>
	out<span class="token punctuation">.</span><span class="token function">writeLong</span><span class="token punctuation">(</span>downFlow<span class="token punctuation">)</span><span class="token punctuation">;</span>
	out<span class="token punctuation">.</span><span class="token function">writeLong</span><span class="token punctuation">(</span>sumFlow<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div></li> <li><p>重写反序列化方法</p> <div class="language-java extra-class"><pre class="language-java"><code><span class="token annotation punctuation">@Override</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">readFields</span><span class="token punctuation">(</span><span class="token class-name">DataInput</span> in<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">IOException</span> <span class="token punctuation">{</span>
	upFlow <span class="token operator">=</span> in<span class="token punctuation">.</span><span class="token function">readLong</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	downFlow <span class="token operator">=</span> in<span class="token punctuation">.</span><span class="token function">readLong</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	sumFlow <span class="token operator">=</span> in<span class="token punctuation">.</span><span class="token function">readLong</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div></li> <li><p>注意反序列化的顺序和序列化的顺序完全一致</p></li> <li><p>要想把结果显示在文件中，需要重写 toString()，可用”\t”分开，方便后续用</p></li> <li><p>如果需要将自定义的 bean 放在 key 中传输，则还需要实现 Comparable 接口，因为 MapReduce 框中的 Shuffle 过程要求对 key 必须能排序</p> <div class="language-java extra-class"><pre class="language-java"><code><span class="token annotation punctuation">@Override</span>
<span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">compareTo</span><span class="token punctuation">(</span><span class="token class-name">FlowBean</span> o<span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token comment">// 倒序排列，从大到小</span>
	<span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span>sumFlow <span class="token operator">&gt;</span> o<span class="token punctuation">.</span><span class="token function">getSumFlow</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">?</span> <span class="token operator">-</span><span class="token number">1</span> <span class="token operator">:</span> <span class="token number">1</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div></li></ol> <h4 id="_2-3-序列化案例实操"><a href="#_2-3-序列化案例实操" class="header-anchor">#</a> 2.3 序列化案例实操</h4> <p>1、需求：统计每一个手机号耗费的总上行流量、下行流量、总流量</p> <p>​    ① 输入数据 phone_data .txt</p> <p>​	② 输入数据格式：</p> <p><img src="https://imgkr.cn-bj.ufileos.com/883a403a-23e7-46ae-85f0-2ee6e6706c34.png" alt="image-20200723183657595"></p> <p>​	③ 期望输出数据格式</p> <p><img src="https://imgkr.cn-bj.ufileos.com/4c27e7ef-9adb-41ab-8d70-a5b6db428309.png" alt=""></p> <p>2、需求分析</p> <p><img src="https://imgkr.cn-bj.ufileos.com/d75006cd-24a9-48a6-ac7f-a738979c0584.png" alt=""></p> <p>3、编写 MapReduce 程序</p> <p>① 编写流量统计的 Bean 对象</p> <div class="language-java extra-class"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">FlowBean</span> <span class="token keyword">implements</span> <span class="token class-name">Writable</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> <span class="token keyword">long</span> upFlow<span class="token punctuation">;</span><span class="token comment">// 上行流量</span>
    <span class="token keyword">private</span> <span class="token keyword">long</span> downFlow<span class="token punctuation">;</span><span class="token comment">// 下行流量</span>
    <span class="token keyword">private</span> <span class="token keyword">long</span> sumFlow<span class="token punctuation">;</span><span class="token comment">// 总流量</span>

    <span class="token comment">// 空参构造， 为了后续反射用</span>
    <span class="token keyword">public</span> <span class="token class-name">FlowBean</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">super</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token class-name">FlowBean</span><span class="token punctuation">(</span><span class="token keyword">long</span> upFlow<span class="token punctuation">,</span> <span class="token keyword">long</span> downFlow<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">super</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>upFlow <span class="token operator">=</span> upFlow<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>downFlow <span class="token operator">=</span> downFlow<span class="token punctuation">;</span>
        sumFlow <span class="token operator">=</span> upFlow <span class="token operator">+</span> downFlow<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment">// 序列化方法</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">write</span><span class="token punctuation">(</span><span class="token class-name">DataOutput</span> out<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">IOException</span> <span class="token punctuation">{</span>

        out<span class="token punctuation">.</span><span class="token function">writeLong</span><span class="token punctuation">(</span>upFlow<span class="token punctuation">)</span><span class="token punctuation">;</span>
        out<span class="token punctuation">.</span><span class="token function">writeLong</span><span class="token punctuation">(</span>downFlow<span class="token punctuation">)</span><span class="token punctuation">;</span>
        out<span class="token punctuation">.</span><span class="token function">writeLong</span><span class="token punctuation">(</span>sumFlow<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment">// 反序列化方法</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">readFields</span><span class="token punctuation">(</span><span class="token class-name">DataInput</span> in<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">IOException</span> <span class="token punctuation">{</span>
        <span class="token comment">// 必须要求和序列化方法顺序一致</span>
        upFlow <span class="token operator">=</span> in<span class="token punctuation">.</span><span class="token function">readLong</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        downFlow <span class="token operator">=</span> in<span class="token punctuation">.</span><span class="token function">readLong</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        sumFlow <span class="token operator">=</span> in<span class="token punctuation">.</span><span class="token function">readLong</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> upFlow <span class="token operator">+</span> <span class="token string">&quot;\t&quot;</span> <span class="token operator">+</span> downFlow <span class="token operator">+</span> <span class="token string">&quot;\t&quot;</span> <span class="token operator">+</span> sumFlow<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">long</span> <span class="token function">getUpFlow</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> upFlow<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setUpFlow</span><span class="token punctuation">(</span><span class="token keyword">long</span> upFlow<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>upFlow <span class="token operator">=</span> upFlow<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">long</span> <span class="token function">getDownFlow</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> downFlow<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setDownFlow</span><span class="token punctuation">(</span><span class="token keyword">long</span> downFlow<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>downFlow <span class="token operator">=</span> downFlow<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">long</span> <span class="token function">getSumFlow</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> sumFlow<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setSumFlow</span><span class="token punctuation">(</span><span class="token keyword">long</span> sumFlow<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>sumFlow <span class="token operator">=</span> sumFlow<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">set</span><span class="token punctuation">(</span><span class="token keyword">long</span> upFlow2<span class="token punctuation">,</span> <span class="token keyword">long</span> downFlow2<span class="token punctuation">)</span> <span class="token punctuation">{</span>

        upFlow <span class="token operator">=</span> upFlow2<span class="token punctuation">;</span>
        downFlow <span class="token operator">=</span> downFlow2<span class="token punctuation">;</span>
        sumFlow <span class="token operator">=</span> upFlow2 <span class="token operator">+</span> downFlow2<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p>② 编写 mapper</p> <div class="language-java extra-class"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">FlowCountMapper</span> <span class="token keyword">extends</span> <span class="token class-name">Mapper</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">LongWritable</span><span class="token punctuation">,</span> <span class="token class-name">Text</span><span class="token punctuation">,</span> <span class="token class-name">Text</span><span class="token punctuation">,</span> <span class="token class-name">FlowBean</span><span class="token punctuation">&gt;</span></span> <span class="token punctuation">{</span>

    <span class="token class-name">Text</span> k <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Text</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">FlowBean</span> v <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">FlowBean</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">protected</span> <span class="token keyword">void</span> <span class="token function">map</span><span class="token punctuation">(</span><span class="token class-name">LongWritable</span> key<span class="token punctuation">,</span> <span class="token class-name">Text</span> value<span class="token punctuation">,</span> <span class="token class-name">Context</span> context<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">IOException</span><span class="token punctuation">,</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">{</span>
        <span class="token comment">// 7 13560436666 120.196.100.99 1116 954 200</span>

        <span class="token comment">// 1 获取一行</span>
        <span class="token class-name">String</span> line <span class="token operator">=</span> value<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">// 2 切割 \t</span>
        <span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> fields <span class="token operator">=</span> line<span class="token punctuation">.</span><span class="token function">split</span><span class="token punctuation">(</span><span class="token string">&quot;\t&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">// 3 封装对象</span>
        k<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span>fields<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">// 封装手机号</span>

        <span class="token keyword">long</span> upFlow <span class="token operator">=</span> <span class="token class-name">Long</span><span class="token punctuation">.</span><span class="token function">parseLong</span><span class="token punctuation">(</span>fields<span class="token punctuation">[</span>fields<span class="token punctuation">.</span>length <span class="token operator">-</span> <span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">long</span> downFlow <span class="token operator">=</span> <span class="token class-name">Long</span><span class="token punctuation">.</span><span class="token function">parseLong</span><span class="token punctuation">(</span>fields<span class="token punctuation">[</span>fields<span class="token punctuation">.</span>length <span class="token operator">-</span> <span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        v<span class="token punctuation">.</span><span class="token function">setUpFlow</span><span class="token punctuation">(</span>upFlow<span class="token punctuation">)</span><span class="token punctuation">;</span>
        v<span class="token punctuation">.</span><span class="token function">setDownFlow</span><span class="token punctuation">(</span>downFlow<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">//		v.set(upFlow,downFlow);</span>

        <span class="token comment">// 4 写出</span>
        context<span class="token punctuation">.</span><span class="token function">write</span><span class="token punctuation">(</span>k<span class="token punctuation">,</span> v<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p>③ 编写 Reducer 类</p> <div class="language-java extra-class"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">FlowCountReducer</span> <span class="token keyword">extends</span> <span class="token class-name">Reducer</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Text</span><span class="token punctuation">,</span> <span class="token class-name">FlowBean</span><span class="token punctuation">,</span> <span class="token class-name">Text</span><span class="token punctuation">,</span> <span class="token class-name">FlowBean</span><span class="token punctuation">&gt;</span></span> <span class="token punctuation">{</span>

    <span class="token class-name">FlowBean</span> v <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">FlowBean</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">protected</span> <span class="token keyword">void</span> <span class="token function">reduce</span><span class="token punctuation">(</span><span class="token class-name">Text</span> key<span class="token punctuation">,</span> <span class="token class-name">Iterable</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">FlowBean</span><span class="token punctuation">&gt;</span></span> values<span class="token punctuation">,</span> <span class="token class-name">Context</span> context<span class="token punctuation">)</span>
            <span class="token keyword">throws</span> <span class="token class-name">IOException</span><span class="token punctuation">,</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">{</span>
<span class="token comment">//		13568436656	2481	24681    30000</span>
<span class="token comment">//		13568436656	1116	954	 20000</span>

        <span class="token keyword">long</span> sum_upFlow <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token keyword">long</span> sum_downFlow <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
		
        <span class="token comment">// 1 累加求和</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">FlowBean</span> flowBean <span class="token operator">:</span> values<span class="token punctuation">)</span> <span class="token punctuation">{</span>

            sum_upFlow <span class="token operator">+=</span> flowBean<span class="token punctuation">.</span><span class="token function">getUpFlow</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            sum_downFlow <span class="token operator">+=</span> flowBean<span class="token punctuation">.</span><span class="token function">getDownFlow</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        v<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span>sum_upFlow<span class="token punctuation">,</span> sum_downFlow<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">// 2 写出</span>
        context<span class="token punctuation">.</span><span class="token function">write</span><span class="token punctuation">(</span>key<span class="token punctuation">,</span> v<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p>④ 编写 Driver 驱动类</p> <div class="language-java extra-class"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">FlowsumDriver</span> <span class="token punctuation">{</span>

	<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">IOException</span><span class="token punctuation">,</span> <span class="token class-name">ClassNotFoundException</span><span class="token punctuation">,</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">{</span>
		
		args <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">{</span><span class="token string">&quot;e:/input/inputflow&quot;</span><span class="token punctuation">,</span><span class="token string">&quot;e:/output1&quot;</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
		
		<span class="token class-name">Configuration</span> conf <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Configuration</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token comment">// 1 获取job对象</span>
		<span class="token class-name">Job</span> job <span class="token operator">=</span> <span class="token class-name">Job</span><span class="token punctuation">.</span><span class="token function">getInstance</span><span class="token punctuation">(</span>conf <span class="token punctuation">)</span><span class="token punctuation">;</span>
		
		<span class="token comment">// 2 设置jar的路径</span>
		job<span class="token punctuation">.</span><span class="token function">setJarByClass</span><span class="token punctuation">(</span><span class="token class-name">FlowsumDriver</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		
		<span class="token comment">// 3 关联mapper和reducer</span>
		job<span class="token punctuation">.</span><span class="token function">setMapperClass</span><span class="token punctuation">(</span><span class="token class-name">FlowCountMapper</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		job<span class="token punctuation">.</span><span class="token function">setReducerClass</span><span class="token punctuation">(</span><span class="token class-name">FlowCountReducer</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		
		<span class="token comment">// 4 设置mapper输出的key和value类型</span>
		job<span class="token punctuation">.</span><span class="token function">setMapOutputKeyClass</span><span class="token punctuation">(</span><span class="token class-name">Text</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		job<span class="token punctuation">.</span><span class="token function">setMapOutputValueClass</span><span class="token punctuation">(</span><span class="token class-name">FlowBean</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		
		<span class="token comment">// 5 设置最终输出的key和value类型</span>
		job<span class="token punctuation">.</span><span class="token function">setOutputKeyClass</span><span class="token punctuation">(</span><span class="token class-name">Text</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		job<span class="token punctuation">.</span><span class="token function">setOutputValueClass</span><span class="token punctuation">(</span><span class="token class-name">FlowBean</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		
<span class="token comment">//		job.setPartitionerClass(ProvincePartitioner.class);</span>
<span class="token comment">//		</span>
<span class="token comment">//		job.setNumReduceTasks(6);</span>
<span class="token comment">//		</span>
		
		<span class="token comment">// 6 设置输入输出路径</span>
		<span class="token class-name">FileInputFormat</span><span class="token punctuation">.</span><span class="token function">setInputPaths</span><span class="token punctuation">(</span>job<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">Path</span><span class="token punctuation">(</span>args<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token class-name">FileOutputFormat</span><span class="token punctuation">.</span><span class="token function">setOutputPath</span><span class="token punctuation">(</span>job<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">Path</span><span class="token punctuation">(</span>args<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		
		<span class="token comment">// 7 提交job</span>
		<span class="token keyword">boolean</span> result <span class="token operator">=</span> job<span class="token punctuation">.</span><span class="token function">waitForCompletion</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		
		<span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">exit</span><span class="token punctuation">(</span>result<span class="token operator">?</span><span class="token number">0</span> <span class="token operator">:</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><h2 id="三、mapreduce-框架原理"><a href="#三、mapreduce-框架原理" class="header-anchor">#</a> 三、MapReduce 框架原理</h2> <h3 id="_3-1-inputformat-数据输入"><a href="#_3-1-inputformat-数据输入" class="header-anchor">#</a> 3.1 InputFormat 数据输入</h3> <h4 id="_3-1-1-切片与-maptask-并行度决定机制"><a href="#_3-1-1-切片与-maptask-并行度决定机制" class="header-anchor">#</a> 3.1.1 切片与 MapTask 并行度决定机制</h4> <ol><li><p>问题引出</p> <p>MapTask 的并行度决定 Map 阶段的任务处理并发度，进而影响到整个 Job 的处理速度。</p> <p>思考：1G 的数据，启动 8 个 MapTask，可以提高集群的并发处理能力。那么 1K 的数据，也启动 8 个 MapTask，会提高集群性能吗？MapTask 并行任务是否越多越好呢？哪些因素影响了 MapTask 并行度？</p></li> <li><p>MapTask 并行度决定机制</p> <p><strong>数据块</strong>：Block 是 HDFS 物理上把数据分成一块一块。</p> <p><strong>数据切片</strong>：数据切片只是在逻辑上对输入进行分片，并不会在磁盘上将其切分成片进行存储。</p></li></ol> <p><img src="https://imgkr.cn-bj.ufileos.com/a2240c23-3cf4-42dc-b8cb-dfd4969cb795.png" alt=""></p> <h4 id="_3-1-2-job-提交流程源码和切片源码详解"><a href="#_3-1-2-job-提交流程源码和切片源码详解" class="header-anchor">#</a> 3.1.2 Job 提交流程源码和切片源码详解</h4> <p>1．Job 提交流程源码详解，如图 4-8 所示</p> <div class="language-java extra-class"><pre class="language-java"><code><span class="token function">waitForCompletion</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token function">submit</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 1 建立连接</span>
<span class="token function">connect</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 1）创建提交 Job 的代理</span>
<span class="token keyword">new</span> <span class="token class-name">Cluster</span><span class="token punctuation">(</span><span class="token function">getConfiguration</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// （1）判断是本地 yarn 还是远程</span>
<span class="token function">initialize</span><span class="token punctuation">(</span>jobTrackAddr<span class="token punctuation">,</span> conf<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 2 提交 job</span>
submitter<span class="token punctuation">.</span><span class="token function">submitJobInternal</span><span class="token punctuation">(</span><span class="token class-name">Job</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">,</span> cluster<span class="token punctuation">)</span>
<span class="token comment">// 1）创建给集群提交数据的 Stag 路径</span>
<span class="token class-name">Path</span> jobStagingArea <span class="token operator">=</span>
<span class="token class-name">JobSubmissionFiles</span><span class="token punctuation">.</span><span class="token function">getStagingDir</span><span class="token punctuation">(</span>cluster<span class="token punctuation">,</span> conf<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 2）获取 jobid ，并创建 Job 路径</span>
<span class="token class-name">JobID</span> jobId <span class="token operator">=</span> submitClient<span class="token punctuation">.</span><span class="token function">getNewJobID</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 3）拷贝 jar 包到集群</span>
<span class="token function">copyAndConfigureFiles</span><span class="token punctuation">(</span>job<span class="token punctuation">,</span> submitJobDir<span class="token punctuation">)</span><span class="token punctuation">;</span>
rUploader<span class="token punctuation">.</span><span class="token function">uploadFiles</span><span class="token punctuation">(</span>job<span class="token punctuation">,</span> jobSubmitDir<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 4）计算切片，生成切片规划文件</span>
<span class="token function">writeSplits</span><span class="token punctuation">(</span>job<span class="token punctuation">,</span> submitJobDir<span class="token punctuation">)</span><span class="token punctuation">;</span>
maps <span class="token operator">=</span> <span class="token function">writeNewSplits</span><span class="token punctuation">(</span>job<span class="token punctuation">,</span> jobSubmitDir<span class="token punctuation">)</span><span class="token punctuation">;</span>
input<span class="token punctuation">.</span><span class="token function">getSplits</span><span class="token punctuation">(</span>job<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 5）向 Stag 路径写 XML 配置文件</span>
<span class="token function">writeConf</span><span class="token punctuation">(</span>conf<span class="token punctuation">,</span> submitJobFile<span class="token punctuation">)</span><span class="token punctuation">;</span>
conf<span class="token punctuation">.</span><span class="token function">writeXml</span><span class="token punctuation">(</span>out<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 6）提交 Job,返回提交状态</span>
status <span class="token operator">=</span> submitClient<span class="token punctuation">.</span><span class="token function">submitJob</span><span class="token punctuation">(</span>jobId<span class="token punctuation">,</span>
submitJobDir<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> job<span class="token punctuation">.</span><span class="token function">getCredentials</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div><p><img src="https://imgkr.cn-bj.ufileos.com/adfae885-c0a0-47e1-94d9-19976e3aeb85.png" alt=""></p> <p>2．FileInputFormat 切片源码解析(input.getSplits(job))</p> <p>（1）程序先找到你数据存储的目录。</p> <p>（2）开始遍历处理（规划切片）目录下的每一个文件</p> <p>（3）遍历第一个文件ss.txt</p> <p>​		a）获取文件大小fs.sizeOf(ss.txt)</p> <p>​		b）计算切片大小 computeSplitSize(Math.max(minSize,Math.min(maxSize,blocksize)))=blocksize=128M 		c）默认情况下，切片大小=blocksize</p> <p>​		d）开始切，形成第1个切片：ss.txt—0:128M 第2个切片ss.txt—128:256M 第3个切片ss.txt—256M:300M （每次切片时，都要判断切完剩下的部分是否大于块的1.1倍，不大于1.1倍就划分一块切片）</p> <p>​		e）将切片信息写到一个切片规划文件中</p> <p>​		 f）整个切片的核心过程在getSplit()方法中完成</p> <p>​		g）InputSplit只记录了切片的元数据信息，比如起始位置、长度以及所在的节点列表等。</p> <p>（4）提交切片规划文件到YARN上，YARN上的MrAppMaster就可以根据切片规划文件计算开启MapTask个数。</p> <h4 id="_3-1-3-fileinputformat-切片机制"><a href="#_3-1-3-fileinputformat-切片机制" class="header-anchor">#</a> 3.1.3 FileInputFormat 切片机制</h4> <p>1、切片机制</p> <p>（1）简单地按照文件的内容长度进行切片</p> <p>（2）切片大小，默认等于Block大小</p> <p>（3）切片时不考虑数据集整体，而是逐个针对每一个文件单独切片</p> <p>2、案例分析</p> <p><img src="https://imgkr.cn-bj.ufileos.com/f60b287b-5328-42a2-8009-ec1fea3fe7af.png" alt=""></p> <p>（1）源码中计算切片大小的公式</p> <div class="language- extra-class"><pre class="language-text"><code> Math.max(minSize, Math.min(maxSize, blockSize)); 

mapreduce.input.fileinputformat.split.minsize=1  默认值为1 

mapreduce.input.fileinputformat.split.maxsize= Long.MAXValue  默认值Long.MAXValue
</code></pre></div><p>因此，默认情况下，切片大小=blocksize。</p> <p>（2）切片大小设置</p> <p>maxsize（切片最大值）：参数如果调得比blockSize小，则会让切片变小，而且就等于配置的这个参数的值。 minsize（切片最小值）：参数调的比blockSize大，则可以让切片变得比blockSize还大。</p> <p>（3）获取切片信息API</p> <div class="language- extra-class"><pre class="language-text"><code>// 获取切片的文件名称 

String name = inputSplit.getPath().getName();

 // 根据文件类型获取切片信息

 FileSplit inputSplit = (FileSplit) context.getInputSplit();
</code></pre></div><h4 id="_3-1-4-combinetextinputformat-切片机制"><a href="#_3-1-4-combinetextinputformat-切片机制" class="header-anchor">#</a> 3.1.4 CombineTextInputFormat 切片机制</h4> <p>框架默认的 TextInputFormat 切片机制是对任务按文件规划切片，不管文件多小，都会是一个单独的切片，都会交给一个 MapTask，这样如果有大量小文件，就会产生大量的 MapTask，处理效率极其低下。</p> <p>1、应用场景：</p> <p>CombineTextInputFormat 用于小文件过多的场景，它可以将多个小文件从逻辑上规划到 一个切片中，这样，多个小文件就可以交给一个 MapTask 处理。</p> <p>2、虚拟存储切片最大值设置</p> <div class="language- extra-class"><pre class="language-text"><code>CombineTextInputFormat.setMaxInputSplitSize(job, 4194304);// 4m 
</code></pre></div><p>注意：虚拟存储切片最大值设置最好根据实际的小文件大小情况来设置具体的值。</p> <p>3、切片机制</p> <p>生成切片过程包括：虚拟存储过程和切片过程二部分。</p> <p><img src="https://imgkr.cn-bj.ufileos.com/7111778f-3e86-46ec-8404-2e0ffe7dfe31.png" alt=""></p> <p>（1）虚拟存储过程：</p> <p>将输入目录下所有文件大小，依次和设置的 setMaxInputSplitSize 值比较，如果不大于设置的最大值，逻辑上划分一个块。如果输入文件大于设置的最大值且大于两倍， 那么以最大值切割一块；当剩余数据大小超过设置的最大值且不大于最大值 2 倍，此时 将文件均分成 2 个虚拟存储块（防止出现太小切片）。</p> <p>例如 setMaxInputSplitSize 值为 4M，输入文件大小为 8.02M，则先逻辑上分成一个 4M。剩余的大小为 4.02M，如果按照 4M 逻辑划分，就会出现 0.02M 的小的虚拟存储 文件，所以将剩余的 4.02M 文件切分成（2.01M 和 2.01M）两个文件。</p> <p>（2）切片过程：</p> <p>​	（a）判断虚拟存储的文件大小是否大于 setMaxInputSplitSize 值，大于等于则单独 形成一个切片。</p> <p>​	（b）如果不大于则跟下一个虚拟存储文件进行合并，共同形成一个切片。</p> <p>​	（c）测试举例：有 4 个小文件大小分别为 1.7M、5.1M、3.4M 以及 6.8M 这四个小 文件，则虚拟存储之后形成 6 个文件块，大小分别为： 1.7M，（2.55M、2.55M），3.4M 以及（3.4M、3.4M）</p> <p>最终会形成 3 个切片，大小分别为： （1.7+2.55）M，（2.55+3.4）M，（3.4+3.4）M 3.1.5</p> <h4 id="_3-1-5-combinetextinputformat-案例实操"><a href="#_3-1-5-combinetextinputformat-案例实操" class="header-anchor">#</a> 3.1.5 CombineTextInputFormat 案例实操</h4> <p>1．需求</p> <p>将输入的大量小文件合并成一个切片统一处理。</p> <p>（1）输入数据 准备 4 个小文件</p> <p>（2）期望： 期望一个切片处理 4 个文件</p> <p>2．实现过程</p> <p>（1）不做任何处理，运行 1.6 节的 WordCount 案例程序，观察切片个数为 4。</p> <p>（2）在 WordcountDriver 中增加如下代码，运行程序，并观察运行的切片个数为 3。</p> <p>​	 （a）驱动类中添加代码如下：</p> <div class="language- extra-class"><pre class="language-text"><code>// 如果不设置 InputFormat，它默认用的是 TextInputFormat.class
job.setInputFormatClass(CombineTextInputFormat.class);
//虚拟存储切片最大值设置 4m
CombineTextInputFormat.setMaxInputSplitSize(job, 4194304);
</code></pre></div><p>​	（b）运行结果为 3 个切片。</p> <p>（3）在 WordcountDriver 中增加如下代码，运行程序，并观察运行的切片个数为 1。</p> <p>​		（a）驱动中添加代码如下：</p> <div class="language- extra-class"><pre class="language-text"><code>// 如果不设置 InputFormat，它默认用的是 TextInputFormat.class
job.setInputFormatClass(CombineTextInputFormat.class);
//虚拟存储切片最大值设置 20m
CombineTextInputFormat.setMaxInputSplitSize(job, 20971520);
</code></pre></div><p>​	（b）运行结果为 1 个切片。</p> <h4 id="_3-1-6-fileinputformat-实现类"><a href="#_3-1-6-fileinputformat-实现类" class="header-anchor">#</a> 3.1.6 FileInputFormat 实现类</h4> <p>思考：在运行MapReduce程序时，输入的文件格式包括：基于行的日志文件、 二进制格式文件、数据库表等。那么，针对不同的数据类型，MapReduce 是如何读取这些数据的呢？</p> <p>FileInputFormat 常见的接口实现类包括： TextInputFormat 、 KeyValueTextInputFormat、NLineInputFormat、CombineTextInputFormat和自定义 InputFormat等。</p> <h5 id="_1-textinputformat"><a href="#_1-textinputformat" class="header-anchor">#</a> 1．TextInputFormat</h5> <p>TextInputFormat是默认的FileInputFormat实现类。按行读取每条记录。键是存储该行在整个文件中的 起始字节偏移量， LongWritable类 型。值是这行的内容，不包括任何行终止符（换行符和回车符）， Text类型。</p> <p>以下是一个示例，比如，一个分片包含了如下4条文本记录。</p> <div class="language- extra-class"><pre class="language-text"><code>Rich learning form
Intelligent learning engine
Learning more convenient
From the real demand for more close to the enterprise
</code></pre></div><p>每条记录表示为以下键/值对：</p> <div class="language- extra-class"><pre class="language-text"><code>(0,Rich learning form)
(19,Intelligent learning engine)
(47,Learning more convenient)
(72,From the real demand for more close to the enterprise)
</code></pre></div><h5 id="_2-keyvaluetextinputformat"><a href="#_2-keyvaluetextinputformat" class="header-anchor">#</a> 2．KeyValueTextInputFormat</h5> <p>每 一 行 均 为 一 条 记 录 ， 被 分 隔 符 分 割 为 key ， value 。 可 以 通 过 在 驱 动 类 中 设 置 conf.set(KeyValueLineRecordReader.KEY_VALUE_SEPERATOR, &quot;\t&quot;); 来设定分隔符。默认分隔符是tab（\t）。</p> <p>以下是一个示例，输入是一个包含4条记录的分片。其中——&gt;表示一个（水平方向的）制表符。</p> <div class="language- extra-class"><pre class="language-text"><code>line1 ——&gt;Rich learning form
line2 ——&gt;Intelligent learning engine
line3 ——&gt;Learning more convenient
line4 ——&gt;From the real demand for more close to the enterprise
</code></pre></div><p>每条记录表示为以下键/值对：</p> <div class="language- extra-class"><pre class="language-text"><code>(line1,Rich learning form)
(line2,Intelligent learning engine)
(line3,Learning more convenient)
(line4,From the real demand for more close to the enterprise)
</code></pre></div><p>此时的键是每行排在制表符之前的Text序列。</p> <h5 id="_3-nlineinputformat"><a href="#_3-nlineinputformat" class="header-anchor">#</a> 3．NLineInputFormat</h5> <p>如 果 使 用 NlineInputFormat ， 代表每个 map 进 程 处 理 的 InputSplit 不再按 Block 块 去 划 分 ， 而 是 按 NlineInputFormat指定的行数N来划分。即输入文件的总行数/N=切片数，如果不整除，切片数=商+1。 以下是一个示例，仍然以上面的4行输入为例。</p> <div class="language- extra-class"><pre class="language-text"><code>Rich learning form
Intelligent learning engine
Learning more convenient
From the real demand for more close to the enterprise
</code></pre></div><p>例如，如果N是2，则每个输入分片包含两行。开启2个MapTask。</p> <div class="language- extra-class"><pre class="language-text"><code>(0,Rich learning form)
(19,Intelligent learning engine)
</code></pre></div><p>另一个 mapper 则收到后两行：</p> <div class="language- extra-class"><pre class="language-text"><code>(47,Learning more convenient)
(72,From the real demand for more close to the enterprise)
</code></pre></div><p>这里的键和值与TextInputFormat生成的一样。</p> <h4 id="_3-1-7-keyvaluetextinputformat-使用案例"><a href="#_3-1-7-keyvaluetextinputformat-使用案例" class="header-anchor">#</a> 3.1.7 KeyValueTextInputFormat 使用案例</h4> <p>1．需求</p> <p>统计输入文件中每一行的第一个单词相同的行数。</p> <p>（1）输入数据</p> <div class="language- extra-class"><pre class="language-text"><code>banzhang ni hao
xihuan hadoop banzhang
banzhang ni hao
xihuan hadoop banzhang
</code></pre></div><p>（2）期望结果数据</p> <div class="language- extra-class"><pre class="language-text"><code>banzhang 2
xihuan 2
</code></pre></div><p>2．需求分析</p> <p><img src="https://imgkr.cn-bj.ufileos.com/5c536c82-af5c-410c-9245-8fdacce6ab9b.png" alt=""></p> <p>code: priv.starfish.hadoop.mr.kv</p> <h4 id="_3-1-8-nlineinputformat-使用案例"><a href="#_3-1-8-nlineinputformat-使用案例" class="header-anchor">#</a> 3.1.8 NLineInputFormat 使用案例</h4> <p>1．需求</p> <p>对每个单词进行个数统计，要求根据每个输入文件的行数来规定输出多少个切片。此案 例要求每三行放入一个切片中。</p> <p>（1）输入数据</p> <div class="language- extra-class"><pre class="language-text"><code>banzhang ni hao
xihuan hadoop banzhang
banzhang ni hao
xihuan hadoop banzhang
banzhang ni hao
xihuan hadoop banzhang
banzhang ni hao
xihuan hadoop banzhang
banzhang ni hao
xihuan hadoop banzhang banzhang ni hao
xihuan hadoop banzhang
</code></pre></div><p>（2）期望输出数据</p> <div class="language- extra-class"><pre class="language-text"><code>Number of splits:4
</code></pre></div><p>2．需求分析</p> <p><img src="https://imgkr.cn-bj.ufileos.com/06bf6edf-4763-465f-bcd3-d228d0524998.png" alt=""></p> <p>3．代码实现</p> <div class="language- extra-class"><pre class="language-text"><code>priv.starfish.hadoop.mr.nline包下
</code></pre></div><p>4．测试 （1）输入数据</p> <div class="language- extra-class"><pre class="language-text"><code>banzhang ni hao
xihuan hadoop banzhang
banzhang ni hao
xihuan hadoop banzhang
banzhang ni hao
xihuan hadoop banzhang
banzhang ni hao
xihuan hadoop banzhang
banzhang ni hao
xihuan hadoop banzhang banzhang ni hao
</code></pre></div><p>（2）输出结果的切片数，如图 4-10 所示：</p> <p><img src="https://imgkr.cn-bj.ufileos.com/245975cc-6eb9-4e48-ad70-aa99c30e371e.png" alt=""></p> <h4 id="_3-1-9-自定义-inputformat"><a href="#_3-1-9-自定义-inputformat" class="header-anchor">#</a> 3.1.9 自定义 InputFormat</h4> <p>在企业开发中，Hadoop框架自带的InputFormat类型不能满足所有应用场 景，需要自定义InputFormat来解决实际问题。 自定义InputFormat步骤如下：</p> <p>（1）自定义一个类继承FileInputFormat。</p> <p>（2）改写RecordReader，实现一次读取一个完整文件封装为KV。</p> <p>（3）在输出时使用SequenceFileOutPutFormat输出合并文件。</p> <h4 id="_3-1-10-自定义-inputformat-案例实操"><a href="#_3-1-10-自定义-inputformat-案例实操" class="header-anchor">#</a> 3.1.10 自定义 InputFormat 案例实操</h4> <p>无论 HDFS 还是 MapReduce，在处理小文件时效率都非常低，但又难免面临处理大量 小文件的场景，此时，就需要有相应解决方案。可以自定义 InputFormat 实现小文件的合并。</p> <p>1．需求</p> <p>将多个小文件合并成一个 SequenceFile 文件（SequenceFile 文件是 Hadoop 用来存储二 进制形式的 key-value 对的文件格式），SequenceFile 里面存储着多个文件，存储的形式为文 件路径+名称为 key，文件内容为 value。</p> <p>（1）输入数据</p> <p><img src="https://imgkr.cn-bj.ufileos.com/311531ae-4e34-4510-a824-ef931a4bae7b.png" alt="image-20200724153412425"></p> <p>（2）期望输出文件格式</p> <p><img src="https://imgkr.cn-bj.ufileos.com/8f18a0f7-7fbd-42ad-bc3b-cc5a09e5692b.png" alt="image-20200724153427396"></p> <p>2．需求分析</p> <p>1、自定义一个类继承FileInputFormat</p> <p>（1）重写isSplitable()方法，返回false不可切割</p> <p>（2）重写createRecordReader()，创建自定义的RecordReader对象，并初始化</p> <p>2、改写RecordReader，实现一次读取一个完整文件封装为KV</p> <p>（1）采用IO流一次读取一个文件输出到value中，因为设置了不可切片，最终把所有文件都封装到了value中 （2）获取文件路径信息+名称，并设置key</p> <p>3、设置Driver</p> <div class="language- extra-class"><pre class="language-text"><code>// （1）设置输入的inputFormat

 job.setInputFormatClass(WholeFileInputformat.class); 

// （2）设置输出的outputFormat 

job.setOutputFormatClass(SequenceFileOutputFormat.class);
</code></pre></div><p>3．程序实现</p> <div class="language- extra-class"><pre class="language-text"><code>priv.starfish.hadoop.mr.inputformat包
</code></pre></div><h3 id="_3-2-mapreduce-工作流程"><a href="#_3-2-mapreduce-工作流程" class="header-anchor">#</a> 3.2 MapReduce 工作流程</h3> <p>1．流程示意图，如图 4-6，4-7 所示</p> <p><img src="https://imgkr.cn-bj.ufileos.com/26929967-2e21-4ed2-8fc2-0da3ab759204.png" alt=""></p> <p><img src="https://imgkr.cn-bj.ufileos.com/7a10044f-c359-4cb7-80eb-09782bd39af8.png" alt=""></p> <p>2．流程详解</p> <p>上面的流程是整个 MapReduce 最全工作流程，但是 Shuffle 过程只是从第 7 步开始到第 16 步结束，具体 Shuffle 过程详解，如下：</p> <ol><li>MapTask 收集我们的 map()方法输出的 kv 对，放到内存缓冲区中</li> <li>从内存缓冲区不断溢出本地磁盘文件，可能会溢出多个文件</li> <li>多个溢出文件会被合并成大的溢出文件</li> <li>在溢出过程及合并的过程中，都要调用 Partitioner 进行分区和针对 key 进行排序</li> <li>ReduceTask 根据自己的分区号，去各个 MapTask 机器上取相应的结果分区数据</li> <li>ReduceTask 会取到同一个分区的来自不同 MapTask 的结果文件，ReduceTask 会将这 些文件再进行合并（归并排序）</li> <li>合并成大文件后，Shuffle 的过程也就结束了，后面进入 ReduceTask 的逻辑运算过程 （从文件中取出一个一个的键值对 Group，调用用户自定义的 reduce()方法）</li></ol> <p>3．注意</p> <p>Shuffle 中的缓冲区大小会影响到 MapReduce 程序的执行效率，原则上说，缓冲区越大， 磁盘 io 的次数越少，执行速度就越快。</p> <p>缓冲区的大小可以通过参数调整，参数：io.sort.mb 默认 100M。</p> <p>4．源码解析流程</p> <div class="language- extra-class"><pre class="language-text"><code>context.write(k, NullWritable.get());
output.write(key, value);
collector.collect(key, value,partitioner.getPartition(key, value, partitions));
HashPartitioner();
collect()
close()
collect.flush()
sortAndSpill()
sort() QuickSort
mergeParts();
collector.close();

</code></pre></div><h3 id="_3-3-shuffle-机制"><a href="#_3-3-shuffle-机制" class="header-anchor">#</a> 3.3 Shuffle 机制</h3> <h4 id="_3-3-1-shuffle-机制"><a href="#_3-3-1-shuffle-机制" class="header-anchor">#</a> 3.3.1 Shuffle 机制</h4> <p>Map 方法之后，Reduce 方法之前的数据处理过程称之为 Shuffle。如图 4-14 所示。</p> <p><img src="https://imgkr.cn-bj.ufileos.com/19fe35b4-d486-488e-afbd-cfeea4ae3093.png" alt=""></p> <h4 id="_3-3-2-partition-分区"><a href="#_3-3-2-partition-分区" class="header-anchor">#</a> 3.3.2 Partition 分区</h4> <p>1、问题引出</p> <p>要求将统计结果按照条件输出到不同文件中（分区）。比如：将统计结果 按照手机归属地不同省份输出到不同文件中（分区）</p> <p>2、默认Partitioner分区</p> <div class="language- extra-class"><pre class="language-text"><code>public class HashPartitioner&lt;K, V&gt; extends Partitioner&lt;K, V&gt; {
	public int getPartition(K key, V value, int numReduceTasks) {
	return (key.hashCode() &amp; Integer.MAX_VALUE) % numReduceTasks;
	}
}
</code></pre></div><p>默认分区是根据key的hashCode对ReduceTasks个数取模得到的。用户没法 控制哪个key存储到哪个分区。</p> <p>3、自定义Partitioner步骤</p> <p>（1）自定义类继承Partitioner，重写getPartition()方法</p> <div class="language- extra-class"><pre class="language-text"><code>public class CustomPartitioner extends Partitioner&lt;Text, FlowBean&gt; {
	@Override
	public int getPartition(Text key, FlowBean value, int numPartitions) {
	// 控制分区代码逻辑
	… …
	return partition;
	}
}
</code></pre></div><p>（2）在Job驱动中，设置自定义Partitioner</p> <div class="language- extra-class"><pre class="language-text"><code> job.setPartitionerClass(CustomPartitioner.class); 
</code></pre></div><p>（3）自定义Partition后，要根据自定义Partitioner的逻辑设置相应数量的ReduceTask</p> <div class="language- extra-class"><pre class="language-text"><code>job.setNumReduceTasks(5);
</code></pre></div><p>4、分区总结</p> <p>（1）如果ReduceTask的数量&gt; getPartition的结果数，则会多产生几个空的输出文件part-r-000xx；</p> <p>（2）如果1&lt;ReduceTask的数量&lt;getPartition的结果数，则有一部分分区数据无处安放，会Exception；</p> <p>（3）如 果ReduceTask的数量=1，则不管MapTask端输出多少个分区文件，最终结果都交给这一个 ReduceTask，最终也就只会产生一个结果文件 part-r-00000；</p> <p>（4）分区号必须从零开始，逐一累加。</p> <p>5、案例分析</p> <p>例如：假设自定义分区数为5，则</p> <p>（1）job.setNumReduceTasks(1); 会正常运行，只不过会产生一个输出文件</p> <p>（2）job.setNumReduceTasks(2); 会报错</p> <p>（3）job.setNumReduceTasks(6);   大于5，程序会正常运行，会产生空文件</p> <h4 id="_3-3-3-partition-分区案例实操"><a href="#_3-3-3-partition-分区案例实操" class="header-anchor">#</a> 3.3.3 Partition 分区案例实操</h4> <p>1．需求 将统计结果按照手机归属地不同省份输出到不同文件中（分区）</p> <p>（1）输入数据  phone_data .txt</p> <p>（2）期望输出数据</p> <p>手机号 136、137、138、139 开头都分别放到一个独立的 4 个文件中，其他开头的放到 一个文件中。</p> <p>2．需求分析</p> <p>1、需求：将统计结果按照手机归属地不同省份输出到不同文件中（分区）</p> <p><img src="https://imgkr.cn-bj.ufileos.com/f3319436-9a53-46d0-91be-5acc130f95e1.png" alt="image-20200724154510165"></p> <p>3．在案例 2.4 的基础上，增加一个分区类</p> <p>4．在驱动函数中增加自定义数据分区设置和 ReduceTask 设置</p> <div class="language- extra-class"><pre class="language-text"><code>priv.starfish.hadoop.mr.flowsum ProvincePartitioner类
</code></pre></div><h4 id="_3-3-4-writablecomparable-排序"><a href="#_3-3-4-writablecomparable-排序" class="header-anchor">#</a> 3.3.4 WritableComparable 排序</h4> <p>排序是MapReduce框架中最重要的操作之一。</p> <p>MapTask和ReduceTask均会对数 据按 照key进 行排 序。该操作属于 Hadoop的默认行为。任何应用程序中的数据均会被排序，而不管逻辑上是 否需要。 默认排序是按照字典顺序排序，且实现该排序的方法是快速排序。</p> <p>对于MapTask，它会将处理的结果暂时放到环形缓冲区中，当环形缓冲区使 用率达到一定阈值后，再对缓冲区中的数据进行一次快速排序，并将这些有序数 据溢写到磁盘上，而当数据处理完毕后，它会对磁盘上所有文件进行归并排序。</p> <p>对于ReduceTask，它从每个MapTask上远程拷贝相应的数据文件，如果文件大 小超过一定阈值，则溢写磁盘上，否则存储在内存中。如果磁盘上文件数目达到 一定阈值，则进行一次归并排序以生成一个更大文件；如果内存中文件大小或者 数目超过一定阈值，则进行一次合并后将数据溢写到磁盘上。当所有数据拷贝完 毕后，ReduceTask统一对内存和磁盘上的所有数据进行一次归并排序。</p> <p>1．排序的分类</p> <p>（1）部分排序</p> <p>MapReduce根据输入记录的键对数据集排序。保证输出的每个文件内部有序。</p> <p>（2）全排序</p> <p>最终输出结果只有一个文件，且文件内部有序。实现方式是只设置一个ReduceTask。但该方法在 处理大型文件时效率极低，因为一台机器处理所有文件，完全丧失了MapReduce所提供的并行架构。</p> <p>（3）辅助排序：（GroupingComparator分组）</p> <p>在Reduce端对key进行分组。应用于：在接收的key为bean对象时，想让一个或几个字段相同（全部 字段比较不相同）的key进入到同一个reduce方法时，可以采用分组排序。</p> <p>（4）二次排序</p> <p>在自定义排序过程中，如果compareTo中的判断条件为两个即为二次排序。</p> <p>2．自定义排序 WritableComparable</p> <p>（1）原理分析</p> <p>bean 对象做为 key 传输，需要实现 WritableComparable 接口重写 compareTo 方法，就可 以实现排序。</p> <div class="language- extra-class"><pre class="language-text"><code>@Override
public int compareTo(FlowBean o) {
int result;
// 按照总流量大小，倒序排列
if (sumFlow &gt; bean.getSumFlow()) {
result = -1;
}else if (sumFlow &lt; bean.getSumFlow()) {
result = 1;
}else {
result = 0;
}
return result;
}

</code></pre></div><h4 id="_3-3-5-writablecomparable-排序案例实操-全排序"><a href="#_3-3-5-writablecomparable-排序案例实操-全排序" class="header-anchor">#</a> 3.3.5 WritableComparable 排序案例实操（全排序）</h4> <p>1．需求</p> <p>根据案例 2.3 产生的结果再次对总流量进行排序。</p> <p>（1）输入数据</p> <p>原始数据 phone_data .txt</p> <p>第一次处理后的数据 part-r-00000</p> <p>（2）期望输出数据</p> <div class="language- extra-class"><pre class="language-text"><code>13509468723 7335 110349 117684
13736230513 2481 24681 27162
13956435636 132 1512 1644
13846544121 264 0 264
。。。 。。。

</code></pre></div><p>2．需求分析</p> <p><img src="https://imgkr.cn-bj.ufileos.com/d5cb65cd-3a55-492b-8279-499bed05cc3e.png" alt=""></p> <p>3．代码实现</p> <div class="language- extra-class"><pre class="language-text"><code>priv.starfish.hadoop.mr.sort
</code></pre></div><h4 id="_3-3-6-writablecomparable-排序案例实操-区内排序"><a href="#_3-3-6-writablecomparable-排序案例实操-区内排序" class="header-anchor">#</a> 3.3.6 WritableComparable 排序案例实操（区内排序）</h4> <p>1．需求</p> <p>要求每个省份手机号输出的文件中按照总流量内部排序。</p> <p>2．需求分析</p> <p>基于前一个需求，增加自定义分区类，分区按照省份手机号设置。</p> <p><img src="https://imgkr.cn-bj.ufileos.com/2aef3942-35a7-43eb-9157-8437f1d1444e.png" alt=""></p> <p>3．案例实操</p> <p>（1）增加自定义分区类</p> <div class="language- extra-class"><pre class="language-text"><code>priv.starfish.hadoop.mr.sort ProvincePartitioner
</code></pre></div><p>（2）在驱动类中添加分区类</p> <div class="language- extra-class"><pre class="language-text"><code>// 加载自定义分区类
job.setPartitionerClass(ProvincePartitioner.class);
// 设置 Reducetask 个数
job.setNumReduceTasks(5);

</code></pre></div><h4 id="_3-3-7-combiner-合并"><a href="#_3-3-7-combiner-合并" class="header-anchor">#</a> 3.3.7 Combiner 合并</h4> <p>（1）Combiner是MR程序中Mapper和Reducer之外的一种组件。</p> <p>（2）Combiner组件的父类就是Reducer。</p> <p>（3）Combiner和Reducer的区别在于运行的位置</p> <ul><li><p>Combiner是在每一个MapTask所在的节点运行;</p></li> <li><p>Reducer是接收全局所有Mapper的输出结果；</p></li></ul> <p>（4）Combiner的意义就是对每一个MapTask的输出进行局部汇总，以减小网络传输量。</p> <p>（5）Combiner能够应用的前提是不能影响最终的业务逻辑，而且，Combiner的输出kv 应该跟Reducer的输入kv类型要对应起来。</p> <p>（6）自定义 Combiner 实现步骤</p> <p>​	（a）自定义一个 Combiner 继承 Reducer，重写 Reduce 方法</p> <div class="language- extra-class"><pre class="language-text"><code>public class WordcountCombiner extends Reducer&lt;Text, IntWritable, Text,IntWritable&gt;{
@Override
protected void reduce(Text key, Iterable&lt;IntWritable&gt;
values,Context context) throws IOException,
InterruptedException {
 // 1 汇总操作
int count = 0;
for(IntWritable v :values){
count += v.get();
}
 // 2 写出
context.write(key, new IntWritable(count));
}
}
</code></pre></div><p>（b）在 Job 驱动类中设置：</p> <div class="language- extra-class"><pre class="language-text"><code>job.setCombinerClass(WordcountCombiner.class);
</code></pre></div><h4 id="_3-3-8-combiner-合并案例实操"><a href="#_3-3-8-combiner-合并案例实操" class="header-anchor">#</a> 3.3.8 Combiner 合并案例实操</h4> <p>1．需求</p> <p>统计过程中对每一个 MapTask 的输出进行局部汇总，以减小网络传输量即采用 Combiner 功能。</p> <p>（1）数据输入  hello.txt</p> <p>（2）期望输出数据</p> <p>期望：Combine 输入数据多，输出时经过合并，输出数据降低。</p> <p>2．需求分析</p> <p><img src="https://imgkr.cn-bj.ufileos.com/1f301c7a-675e-4f1e-b647-5dd55adf232a.png" alt=""></p> <p>3．案例实操-方案一</p> <p>1）增加一个 WordcountCombiner 类继承 Reducer</p> <div class="language- extra-class"><pre class="language-text"><code>import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class WordcountCombiner extends Reducer&lt;Text,
IntWritable, Text, IntWritable&gt;{
IntWritable v = new IntWritable();
@Override
protected void reduce(Text key, Iterable&lt;IntWritable&gt;
values, Context context) throws IOException,
InterruptedException {
 // 1 汇总
int sum = 0;
for(IntWritable value :values){
sum += value.get();
}
v.set(sum);
// 2 写出
context.write(key, v);
}
}

</code></pre></div><p>2）在 WordcountDriver 驱动类中指定 Combiner</p> <div class="language- extra-class"><pre class="language-text"><code>// 指定需要使用 combiner，以及用哪个类作为 combiner 的逻辑
job.setCombinerClass(WordcountCombiner.class);

</code></pre></div><p>4．案例实操-方案二</p> <p>1）将 WordcountReducer 作为 Combiner 在 WordcountDriver 驱动类中指定</p> <div class="language- extra-class"><pre class="language-text"><code>// 指定需要使用 Combiner，以及用哪个类作为 Combiner 的逻辑
job.setCombinerClass(WordcountReducer.class);

</code></pre></div><p>运行程序，如图 4-16，4-17 所示</p> <p><img src="https://imgkr.cn-bj.ufileos.com/c0935098-c23f-4be9-8f3b-812bc11833aa.png" alt="image-20200724174441853"></p> <h4 id="_3-3-9-groupingcomparator-分组-辅助排序"><a href="#_3-3-9-groupingcomparator-分组-辅助排序" class="header-anchor">#</a> 3.3.9 GroupingComparator 分组（辅助排序）</h4> <p>对 Reduce 阶段的数据根据某一个或几个字段进行分组。</p> <p>分组排序步骤：</p> <p>（1）自定义类继承 WritableComparator</p> <p>（2）重写 compare()方法</p> <div class="language- extra-class"><pre class="language-text"><code>@Override public int compare(WritableComparable a, WritableComparable b) { // 比较的业务逻辑 return result; }
</code></pre></div><p>（3）创建一个构造将比较对象的类传给父类</p> <div class="language- extra-class"><pre class="language-text"><code>protected OrderGroupingComparator() { super(OrderBean.class, true); }
</code></pre></div><h4 id="_3-3-10-groupingcomparator-分组案例实操"><a href="#_3-3-10-groupingcomparator-分组案例实操" class="header-anchor">#</a> 3.3.10 GroupingComparator 分组案例实操</h4> <p>1．需求 有如下订单数据</p> <p><img src="https://imgkr.cn-bj.ufileos.com/f83db6e2-380f-4434-bc5a-e154b720d068.png" alt=""></p> <p>现在需要求出每一个订单中最贵的商品。</p> <p>（1）输入数据 GroupingComparator.txt</p> <p>（2）期望输出数据</p> <div class="language- extra-class"><pre class="language-text"><code>1 222.8
2 722.4
3 232.8
</code></pre></div><p>2．需求分析</p> <p>（1）利用“订单 id 和成交金额”作为 key，可以将 Map 阶段读取到的所有订单数据按 照 id 升序排序，如果 id 相同再按照金额降序排序，发送到 Reduce。</p> <p>（2）在 Reduce 端利用 groupingComparator 将订单 id 相同的 kv 聚合成组，然后取第一 个即是该订单中最贵商品，如图 4-18 所示。</p> <p><img src="https://imgkr.cn-bj.ufileos.com/0d635313-8935-4423-a9f1-d0d8d5940b25.png" alt=""></p> <p>3．代码实现</p> <div class="language- extra-class"><pre class="language-text"><code>priv.starfish.hadoop.mr.order
</code></pre></div><h3 id="_3-4-maptask-工作机制"><a href="#_3-4-maptask-工作机制" class="header-anchor">#</a> 3.4 MapTask 工作机制</h3> <p><img src="https://imgkr.cn-bj.ufileos.com/caae2e63-73a1-49a5-b1f8-e9d090d92bad.png" alt=""></p> <p>（1）Read 阶段：MapTask 通过用户编写的 RecordReader，从输入 InputSplit 中解析出 一个个 key/value。</p> <p>（2）Map 阶段：该节点主要是将解析出的 key/value 交给用户编写 map()函数处理，并 产生一系列新的 key/value。</p> <p>（3）Collect 收集阶段：在用户编写 map()函数中，当数据处理完成后，一般会调用 OutputCollector.collect()输出结果。在该函数内部，它会将生成的 key/value 分区（调用 Partitioner），并写入一个环形内存缓冲区中。</p> <p>（4）Spill 阶段：即“溢写”，当环形缓冲区满后，MapReduce 会将数据写到本地磁盘上， 生成一个临时文件。需要注意的是，将数据写入本地磁盘之前，先要对数据进行一次本地排 序，并在必要时对数据进行合并、压缩等操作。</p> <p>溢写阶段详情：</p> <p>步骤 1：利用快速排序算法对缓存区内的数据进行排序，排序方式是，先按照分区编号 Partition 进行排序，然后按照 key 进行排序。这样，经过排序后，数据以分区为单位聚集在 一起，且同一分区内所有数据按照 key 有序。</p> <p>步骤 2：按照分区编号由小到大依次将每个分区中的数据写入任务工作目录下的临时文 件 output/spillN.out（N 表示当前溢写次数）中。如果用户设置了 Combiner，则写入文件之 前，对每个分区中的数据进行一次聚集操作。</p> <p>步骤 3：将分区数据的元信息写到内存索引数据结构 SpillRecord 中，其中每个分区的元 信息包括在临时文件中的偏移量、压缩前数据大小和压缩后数据大小。如果当前内存索引大 小超过 1MB，则将内存索引写到文件 output/spillN.out.index 中。</p> <p>（5）Combine 阶段：当所有数据处理完成后，MapTask 对所有临时文件进行一次合并， 以确保最终只会生成一个数据文件。</p> <p>当所有数据处理完后，MapTask 会将所有临时文件合并成一个大文件，并保存到文件 output/file.out 中，同时生成相应的索引文件 output/file.out.index。 在进行文件合并过程中，MapTask 以分区为单位进行合并。对于某个分区，它将采用多 轮递归合并的方式。每轮合并 io.sort.factor（默认 10）个文件，并将产生的文件重新加入待 合并列表中，对文件排序后，重复以上过程，直到最终得到一个大文件。</p> <p>让每个 MapTask 最终只生成一个数据文件，可避免同时打开大量文件和同时读取大量 小文件产生的随机读取带来的开销。</p> <h3 id="_3-5-reducetask-工作机制"><a href="#_3-5-reducetask-工作机制" class="header-anchor">#</a> 3.5 ReduceTask 工作机制</h3> <p><img src="https://imgkr.cn-bj.ufileos.com/e8fd10d6-55aa-4de0-9f4c-80c1d3d4b419.png" alt=""></p> <p>（1）Copy 阶段：ReduceTask 从各个 MapTask 上远程拷贝一片数据，并针对某一片数 据，如果其大小超过一定阈值，则写到磁盘上，否则直接放到内存中。</p> <p>（2）Merge 阶段：在远程拷贝数据的同时，ReduceTask 启动了两个后台线程对内存和 磁盘上的文件进行合并，以防止内存使用过多或磁盘上文件过多。</p> <p>（3）Sort 阶段：按照 MapReduce 语义，用户编写 reduce()函数输入数据是按 key 进行 聚集的一组数据。为了将 key 相同的数据聚在一起，Hadoop 采用了基于排序的策略。由于 各个 MapTask 已经实现对自己的处理结果进行了局部排序，因此，ReduceTask 只需对所有 数据进行一次归并排序即可。</p> <p>（4）Reduce 阶段：reduce()函数将计算结果写到 HDFS 上。</p> <p>2．设置 ReduceTask 并行度（个数）</p> <p>ReduceTask 的并行度同样影响整个 Job 的执行并发度和执行效率，但与 MapTask 的并 发数由切片数决定不同，ReduceTask 数量的决定是可以直接手动设置：</p> <div class="language- extra-class"><pre class="language-text"><code>// 默认值是 1，手动设置为 4 

job.setNumReduceTasks(4); 
</code></pre></div><p>3．实验：测试 ReduceTask 多少合适</p> <p>（1）实验环境：1 个 Master 节点，16 个 Slave 节点：CPU:8GHZ，内存: 2G</p> <p>（2）实验结论：</p> <p><img src="https://imgkr.cn-bj.ufileos.com/e28d97eb-befa-4910-b8a3-b5f23a46d9a8.png" alt=""></p> <p>4．注意事项</p> <p>（1）ReduceTask=0，表示没有Reduce阶段，输出文件个数和Map个数一致。</p> <p>（2）ReduceTask默认值就是1，所以输出文件个数为一个。</p> <p>（3）如果数据分布不均匀，就有可能在Reduce阶段产生数据倾斜</p> <p>（4）ReduceTask数量并不是任意设置，还要考虑业务逻辑需求，有些情况下，需要计 算全局汇总结果，就只能有1个ReduceTask。</p> <p>（5）具体多少个ReduceTask，需要根据集群性能而定。</p> <p>（6）如果分区数不是1，但是ReduceTask为1，是否执行分区过程。答案是：不执行分 区过程。因为在MapTask的源码中，执行分区的前提是先判断ReduceNum个数是否大于1。 不大于1肯定不执行。</p> <h3 id="_3-6-outputformat-数据输出"><a href="#_3-6-outputformat-数据输出" class="header-anchor">#</a> 3.6 OutputFormat 数据输出</h3> <h4 id="_3-6-1-outputformat-接口实现类"><a href="#_3-6-1-outputformat-接口实现类" class="header-anchor">#</a> 3.6.1 OutputFormat 接口实现类</h4> <p>OutputFormat是MapReduce输出的基类，所有实现MapReduce输出都实现了 OutputFormat 接口。下面我们介绍几种常见的OutputFormat实现类。</p> <p>1．文本输出TextOutputFormat</p> <p>默 认的输出格式是TextOutputFormat，它把每条记录写为文本行。它的键和值可以是任 意类型，因为TextOutputFormat调用toString()方法把它们转换为字符串。</p> <p>2．SequenceFileOutputFormat</p> <p>将SequenceFileOutputFormat输出作为后续 MapReduce任务的输入，这便是一种好的输出 格式，因为它的格式紧凑，很容易被压缩。</p> <p>3．自定义OutputFormat</p> <p>根据用户需求，自定义实现输出。</p> <h4 id="_3-6-2-自定义-outputformat"><a href="#_3-6-2-自定义-outputformat" class="header-anchor">#</a> 3.6.2 自定义 OutputFormat</h4> <p>1．使用场景</p> <p>为了实现控制最终文件的输出路径和输出格式，可以自定义OutputFormat。 例如：要在一个MapReduce程序中根据数据的不同输出两类结果到不同目 录，这类灵活的输出需求可以通过自定义OutputFormat来实现。</p> <p>2．自定义OutputFormat步骤</p> <p>（1）自定义一个类继承FileOutputFormat。</p> <p>（2）改写RecordWriter，具体改写输出数据的方法write()。</p> <h4 id="_3-6-3-自定义-outputformat-案例实操"><a href="#_3-6-3-自定义-outputformat-案例实操" class="header-anchor">#</a> 3.6.3 自定义 OutputFormat 案例实操</h4> <p>1．需求</p> <p>过滤输入的 log 日志，包含 atguigu 的网站输出到 e:/atguigu.log，不包含 atguigu 的网站 输出到 e:/other.log。 （1）输入数据  log.txt</p> <p>（2）期望输出数据  atguigu.log  other.log</p> <p>2．需求分析</p> <p><img src="https://imgkr.cn-bj.ufileos.com/ffca8111-9117-4252-b27f-724424ad3be8.png" alt=""></p> <p>3．案例实操</p> <div class="language- extra-class"><pre class="language-text"><code>priv.starfish.hadoop.mr.outputformat
</code></pre></div><h3 id="_3-7-join-多种应用"><a href="#_3-7-join-多种应用" class="header-anchor">#</a> 3.7 Join 多种应用</h3> <h4 id="_3-7-1-reduce-join"><a href="#_3-7-1-reduce-join" class="header-anchor">#</a> 3.7.1 Reduce Join</h4> <p>Reduce Join工作原理</p> <p>Map端的主要工作：为来自不同表或文件的key/value对，打标签以区别不同 来源的记录。然后用连接字段作为key，其余部分和新加的标志作为value，最后 进行输出。</p> <p>Reduce端的主要工作：在Reduce端以连接字段作为key的分组已经完成，我 们只需要在每一个分组当中将那些来源于不同文件的记录(在Map阶段已经打标 志)分开，最后进行合并就ok了。</p> <h4 id="_3-7-2-reduce-join-案例实操"><a href="#_3-7-2-reduce-join-案例实操" class="header-anchor">#</a> 3.7.2 Reduce Join 案例实操</h4> <p><img src="https://imgkr.cn-bj.ufileos.com/a38f7498-985f-404a-80ee-e23e10350e37.png" alt=""></p> <p>2．需求分析 通过将关联条件作为 Map 输出的 key，将两表满足 Join 条件的数据并携带数据所来源 的文件信息，发往同一个 ReduceTask，在 Reduce 中进行数据的串联，如图 4-20 所示。</p> <p><img src="https://imgkr.cn-bj.ufileos.com/a95d8957-45c1-4683-9103-ec8cade040cd.png" alt=""></p> <p>3．代码实现 1）创建商品和订合并后的 Bean 类</p> <div class="language- extra-class"><pre class="language-text"><code>priv.starfish.hadoop.mr.table
</code></pre></div><p>4．测试</p> <p>5．总结</p> <p>缺点：这种方式中，合并的操作是在Reduce阶段完成，Reduce端的处理压力 太大，Map节点的运算负载则很低，资源利用率不高，且在Reduce阶段极易产生 数据倾斜。 解决方案：Map端实现数据合并</p> <h4 id="_3-7-3-map-join"><a href="#_3-7-3-map-join" class="header-anchor">#</a> 3.7.3 Map Join</h4> <p>1．使用场景 Map Join 适用于一张表十分小、一张表很大的场景。</p> <p>2．优点</p> <p>思考：在 Reduce 端处理过多的表，非常容易产生数据倾斜。怎么办？</p> <p>在 Map 端缓存多张表，提前处理业务逻辑，这样增加 Map 端业务，减少 Reduce 端数 据的压力，尽可能的减少数据倾斜。</p> <p>3．具体办法：采用 DistributedCache</p> <p>（1）在 Mapper 的 setup 阶段，将文件读取到缓存集合中。</p> <p>（2）在驱动函数中加载缓存。 // 缓存普通文件到 Task 运行节点。</p> <p>job.addCacheFile(new URI(&quot;file://e:/cache/pd.txt&quot;));</p> <h4 id="_3-7-4-map-join-案例实操"><a href="#_3-7-4-map-join-案例实操" class="header-anchor">#</a> 3.7.4 Map Join 案例实操</h4> <p><img src="https://imgkr.cn-bj.ufileos.com/6cde022c-a905-4ce0-8db8-f1ecbaef29de.png" alt=""></p> <p>2．需求分析 MapJoin 适用于关联表中有小表的情形。</p> <p><img src="https://imgkr.cn-bj.ufileos.com/e918c4d2-e8e9-444e-8100-a2ec952bed26.png" alt=""></p> <p>3．实现代码</p> <p>（1）先在驱动模块中添加缓存文件</p> <div class="language- extra-class"><pre class="language-text"><code>priv.starfish.hadoop.mr.cache
</code></pre></div><h3 id="_3-8-计数器应用"><a href="#_3-8-计数器应用" class="header-anchor">#</a> 3.8 计数器应用</h3> <p>Hadoop为每个作业维护若干内置计数器，以描述多项指标。例如，某些计数器记录 已处理的字节数和记录数，使用户可监控已处理的输入数据量和已产生的输出数据量。</p> <p>1．计数器API</p> <p>（1）采用枚举的方式统计计数</p> <div class="language- extra-class"><pre class="language-text"><code>enum MyCounter{MALFORORMED,NORMAL}
//对枚举定义的自定义计数器加1
context.getCounter(MyCounter.MALFORORMED).increment(1);
</code></pre></div><p>（2）采用计数器组、计数器名称的方式统计</p> <div class="language- extra-class"><pre class="language-text"><code> context.getCounter(&quot;counterGroup&quot;, &quot;counter&quot;).increment(1); 
</code></pre></div><p>组名和计数器名称随便起，但最好有意义。</p> <p>（3）计数结果在程序运行后的控制台上查看。</p> <ol start="2"><li>计数器案例实操 详见数据清洗案例</li></ol> <h3 id="_3-9-数据清洗-etl"><a href="#_3-9-数据清洗-etl" class="header-anchor">#</a> 3.9 数据清洗（ETL）</h3> <p>在运行核心业务 MapReduce 程序之前，往往要先对数据进行清洗，清理掉不符合用户 要求的数据。清理的过程往往只需要运行 Mapper 程序，不需要运行 Reduce 程序。</p> <h4 id="_3-9-1-数据清洗案例实操-简单解析版"><a href="#_3-9-1-数据清洗案例实操-简单解析版" class="header-anchor">#</a> 3.9.1 数据清洗案例实操-简单解析版</h4> <p>1．需求</p> <p>去除日志中字段长度小于等于 11 的日志。</p> <p>（1）输入数据 web.log</p> <p>（2）期望输出数据 每行字段长度都大于 11。</p> <p>2．需求分析</p> <p>需要在 Map 阶段对输入的数据根据规则进行过滤清洗。</p> <p>3．实现代码</p> <p>（1）编写 LogMapper 类</p> <div class="language- extra-class"><pre class="language-text"><code>priv.starfish.hadoop.mr.log
</code></pre></div><h4 id="_3-9-2-数据清洗案例实操-复杂解析版"><a href="#_3-9-2-数据清洗案例实操-复杂解析版" class="header-anchor">#</a> 3.9.2 数据清洗案例实操-复杂解析版</h4> <p>1．需求</p> <p>对 Web 访问日志中的各字段识别切分，去除日志中不合法的记录。根据清洗规则， 输出过滤后的数据。</p> <p>（1）输入数据 web.log</p> <p>（2）期望输出数据 都是合法的数据</p> <p>2．实现代码</p> <p>（1）定义一个 bean，用来记录日志数据中的各数据字段</p> <h3 id="_3-10-mapreduce-开发总结"><a href="#_3-10-mapreduce-开发总结" class="header-anchor">#</a> 3.10 MapReduce 开发总结</h3> <p>在编写 MapReduce 程序时，需要考虑如下几个方面：</p> <h5 id="_1-输入数据接口-inputformat"><a href="#_1-输入数据接口-inputformat" class="header-anchor">#</a> 1&gt; 输入数据接口：InputFormat</h5> <ol><li>默认使用的实现类是：TextInputFormat</li> <li>TextInputFormat 的功能逻辑是：一次读一行文本，然后将该行的起始偏移量作为 key，行内容作为 value 返回</li> <li>KeyValueTextInputFormat 每一行均为一条记录，被分隔符分割为 key，value。默认分隔符是 tab（\t）</li> <li>NlineInputFormat 按照指定的行数 N 来划分切片</li> <li>CombineTextInputFormat 可以把多个小文件合并成一个切片处理，提高处理效率</li> <li>用户还可以自定义 InputFormat</li></ol> <h5 id="_2-逻辑处理接口-mapper"><a href="#_2-逻辑处理接口-mapper" class="header-anchor">#</a> 2&gt; 逻辑处理接口：Mapper</h5> <p>用户根据业务需求实现其中三个方法：<code>map()</code> <code>setup()</code> <code>cleanup ()</code></p> <h5 id="_3-partitioner-分区"><a href="#_3-partitioner-分区" class="header-anchor">#</a> 3&gt; Partitioner 分区</h5> <ol><li>有默认实现 HashPartitioner ， 逻辑是根据 key 的哈希值 和 numReduces 来返回一个分区号；<code>key.hashCode()&amp;Integer.MAXVALUE % numReduces</code></li> <li>如果业务上有特别的需求，可以自定义分区。</li></ol> <h5 id="_4-comparable-排序"><a href="#_4-comparable-排序" class="header-anchor">#</a> 4&gt; Comparable 排序</h5> <ol><li>当我们用自定义的对象作为 key 来输出时，就必须要实现 WritableComparable 接口，重写其中的compareTo()方法</li> <li>部分排序：对最终输出的每一个文件进行内部排序</li> <li>全排序：对所有数据进行排序，通常只有一个Reduce</li> <li>二次排序：排序的条件有两个</li></ol> <h5 id="_5-combiner合并"><a href="#_5-combiner合并" class="header-anchor">#</a> 5&gt; Combiner合并</h5> <p>Combiner 合并可以提高程序执行效率，减少IO传输。但是使用时必须不能影 响原有的业务处理结果。</p> <h5 id="_6-reduce端分组-groupingcomparator"><a href="#_6-reduce端分组-groupingcomparator" class="header-anchor">#</a> 6&gt; Reduce端分组：GroupingComparator</h5> <p>在 Reduce 端对 key 进行分组。应用于：在接收的 key 为 bean 对象时，想让一个或几个字段相同（全部字段比较不相同）的 key 进入到同一个 reduce 方法时，可以采用分组排序。</p> <h5 id="_7-逻辑处理接口-reducer"><a href="#_7-逻辑处理接口-reducer" class="header-anchor">#</a> 7&gt; 逻辑处理接口：Reducer</h5> <p>用户根据业务需求实现其中三个方法：<code>reduce()</code> <code>setup()</code> <code>cleanup ()</code></p> <h5 id="_8-输出数据接口-outputformat"><a href="#_8-输出数据接口-outputformat" class="header-anchor">#</a> 8&gt; 输出数据接口：OutputFormat</h5> <ol><li>默认实现类是 TextOutputFormat，功能逻辑是：将每一个KV对，向目标文本文件输出一行</li> <li>将 SequenceFileOutputFormat 输出作为后续 MapReduce 任务的输入，这便是一种好的输出格式，因为它的格式紧凑，很容易被压缩</li> <li>用户还可以自定义 OutputFormat</li></ol></div> <footer class="page-edit" style="display:none;"><!----> <!----></footer> <!----> <!----> <!----></main> <!----></div></div></div></div><div class="global-ui"><div class="back-to-ceiling" style="right:1rem;bottom:6rem;width:2.5rem;height:2.5rem;border-radius:.25rem;line-height:2.5rem;display:none;" data-v-db14854a data-v-db14854a><svg t="1574745035067" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5404" class="icon" data-v-db14854a><path d="M526.60727968 10.90185116a27.675 27.675 0 0 0-29.21455937 0c-131.36607665 82.28402758-218.69155461 228.01873535-218.69155402 394.07834331a462.20625001 462.20625001 0 0 0 5.36959153 69.94390903c1.00431239 6.55289093-0.34802892 13.13561351-3.76865779 18.80351572-32.63518765 54.11355614-51.75690182 118.55860487-51.7569018 187.94566865a371.06718723 371.06718723 0 0 0 11.50484808 91.98906777c6.53300375 25.50556257 41.68394495 28.14064038 52.69160883 4.22606766 17.37162448-37.73630017 42.14135425-72.50938081 72.80769204-103.21549295 2.18761121 3.04276886 4.15646224 6.24463696 6.40373557 9.22774369a1871.4375 1871.4375 0 0 0 140.04691725 5.34970492 1866.36093723 1866.36093723 0 0 0 140.04691723-5.34970492c2.24727335-2.98310674 4.21612437-6.18497483 6.3937923-9.2178004 30.66633723 30.70611158 55.4360664 65.4791928 72.80769147 103.21549355 11.00766384 23.91457269 46.15860503 21.27949489 52.69160879-4.22606768a371.15156223 371.15156223 0 0 0 11.514792-91.99901164c0-69.36717486-19.13165746-133.82216804-51.75690182-187.92578088-3.42062944-5.66790279-4.76302748-12.26056868-3.76865837-18.80351632a462.20625001 462.20625001 0 0 0 5.36959269-69.943909c-0.00994388-166.08943902-87.32547796-311.81420293-218.6915546-394.09823051zM605.93803103 357.87693858a93.93749974 93.93749974 0 1 1-187.89594924 6.1e-7 93.93749974 93.93749974 0 0 1 187.89594924-6.1e-7z" p-id="5405" data-v-db14854a></path><path d="M429.50777625 765.63860547C429.50777625 803.39355007 466.44236686 1000.39046097 512.00932183 1000.39046097c45.56695499 0 82.4922232-197.00623328 82.5015456-234.7518555 0-37.75494459-36.9345906-68.35043303-82.4922232-68.34111062-45.57627738-0.00932239-82.52019037 30.59548842-82.51086798 68.34111062z" p-id="5406" data-v-db14854a></path></svg></div><!----></div></div>
    <script src="/assets/js/app.447d4224.js" defer></script><script src="/assets/js/3.9d76740c.js" defer></script><script src="/assets/js/1.c4fd7d2e.js" defer></script><script src="/assets/js/35.de8253eb.js" defer></script>
  </body>
</html>
